Just playing around with laravel-8 unit tests. I extended the basic TestCase and thought laravels factory method would be available. I checked the composer.json and the factories are being loaded.
I am trying to run this particular test but factory
is not found any ideas:
<?php
namespace TestsFeatureHttpControllersAuth;
use IlluminateFoundationTestingRefreshDatabase;
use IlluminateFoundationTestingWithFaker;
use TestsTestCase;
use AppUser;
class LoginControllerTest extends TestCase
{
use RefreshDatabase;
/** @test */
public function login_authenticates_and_redirects_user()
{
$user = factory(User::class)->create();
$response = $this->post(route('login'), [
'email' => $user->email,
'password' => 'password'
]);
$response->assertRedirect(route('home'));
$this->assertAuthenticatedAs($user);
}
}
The error I am getting is:
1) TestsFeatureHttpControllersAuthLoginControllerTest::login_authenticates_and_redirects_user
Error: Call to undefined function TestsFeatureHttpControllersAuthfactory()
asked Oct 17, 2020 at 14:55
m33bom33bo
1,2921 gold badge16 silver badges34 bronze badges
1
- On laravel 8 models are at ‘AppModels’.
- It changes how factory works. See at docs.
So, it should be like:
<?php
namespace TestsFeatureHttpControllersAuth;
use IlluminateFoundationTestingRefreshDatabase;
use IlluminateFoundationTestingWithFaker;
use TestsTestCase;
use AppModelsUser;
class LoginControllerTest extends TestCase
{
use RefreshDatabase;
/** @test */
public function login_authenticates_and_redirects_user()
{
$user = User::factory->create();
$response = $this->post(route('login'), [
'email' => $user->email,
'password' => 'password'
]);
$response->assertRedirect(route('home'));
$this->assertAuthenticatedAs($user);
}
}
answered Dec 9, 2020 at 2:35
Turns out in upgrading to laravel-8 release notes:
- https://laravel.com/docs/8.x/upgrade#seeder-factory-namespaces
«Laravel’s model factories feature has been totally rewritten to support classes and is not compatible with Laravel 7.x style factories.»
So in order to make it work I used:
$user = AppModelsUser::factory(User::class)->make();
answered Oct 17, 2020 at 15:32
m33bom33bo
1,2921 gold badge16 silver badges34 bronze badges
1
684 votes
4 answers
Get the solution ↓↓↓
In laravel I have written the following test:
public function testUserCanCreateAssortment()
{
$this->signIn();
$this->get('/assortments/create')->assertStatus(200);
$this->followingRedirects()
->post('/assortments', $attributes = Assortment::factory()->raw())
->assertSee($attributes['title'])
->assertSee($attributes['description']);
}
}
When I run it with the commandphpunit --filter testUserCanCreateItem
I get the following error:
Error: Call to undefined function Testsfactory()
No idea what is causing it. I have looked at my factories and mytestcase.php
but I could not find a solution. What am I doing wrong?
Mytestcase.php
:
<?php
namespace Tests;
use IlluminateFoundationTestingTestCase as BaseTestCase;
abstract class TestCase extends BaseTestCase
{
use CreatesApplication;
protected function signIn($user = null)
{
$user = $user ?: User::factory()->create();
$this->actingAs($user);
return $user;
}
}
Here the lines the error provides:
/var/www/tests/TestCase.php:13
/var/www/tests/Feature/ItemTest.php:29
2021-11-22
Write your answer
841
votes
Answer
Solution:
In Laravel 8, thefactory
helper is no longer available. Yourtestcase
model class should use HasFactory trait, then you can use your factory like this:
testcase::factory()->count(50)->create();
Please note that you should also update your call to User factory: factory(‘AppUser’)->create()->id;
Here is the relevant documentation:
https://laravel.com/docs/8.x/database-testing#creating-models
However, if you prefer to use the Laravel 7.x style factories, you can use the package laravel/legacy-factories You may install it with composer:
composer require laravel/legacy-factories
622
votes
Answer
Solution:
Guys I found the solution to my answer.
I needed to add the model name in myAssortmentFactory
. So I did:
protected $model = Assortment::class;
and I also needed to import the model by doinguse App/Models/Assortment
.
In theUserFactory
I also needed to import the model by doingApp/Models/Assortment
.
This solved my issue.
375
votes
Answer
Solution:
First run this commandcomposer require laravel/legacy-factories
public function YourMethodName()
{
$user = factory(User::class)->create();
$this->actingAs($user);
//code...
}
303
votes
Answer
Solution:
You may have to specify that you are using an other class.
Did you writeuse Assortment
oruse Assortment
above ?
You can also use the manager to find the class you are using
Share solution ↓
Additional Information:
Date the issue was resolved:
2021-11-22
Link To Source
Link To Answer
People are also looking for solutions of the problem: cannot set properties of undefined (setting ‘_dt_cellindex’)
Didn’t find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
В laravel я написал следующий тест:
public function testUserCanCreateAssortment()
{
$this->signIn();
$this->get('/assortments/create')->assertStatus(200);
$this->followingRedirects()
->post('/assortments', $attributes = Assortment::factory()->raw())
->assertSee($attributes['title'])
->assertSee($attributes['description']);
}
}
Когда я запускаю его с помощью команды phpunit --filter testUserCanCreateItem
, я получаю следующую ошибку:
Error: Call to undefined function Testsfactory()
Не знаю, что это вызывает. Я просмотрел свои заводы и свой testcase.php
, но не смог найти решения. Что я делаю не так?
Мой testcase.php
:
<?php
namespace Tests;
use IlluminateFoundationTestingTestCase as BaseTestCase;
abstract class TestCase extends BaseTestCase
{
use CreatesApplication;
protected function signIn($user = null)
{
$user = $user ?: User::factory()->create();
$this->actingAs($user);
return $user;
}
}
Вот строки, содержащиеся в ошибке:
/var/www/tests/TestCase.php:13
/var/www/tests/Feature/ItemTest.php:29
3 ответа
Лучший ответ
Ребят нашел решение на свой ответ.
Мне нужно было добавить название модели в свой AssortmentFactory
. Так я и сделал:
protected $model = Assortment::class;
И мне также нужно было импортировать модель, выполнив use App/Models/Assortment
.
В laravel я написал следующий тест:…
Это решило мою проблему.
0
Parsa_237
26 Окт 2020 в 16:24
Возможно, вам придется указать, что вы используете другой класс.
Вы писали выше use Assortment
или use Assortment
?
Вы также можете использовать менеджер, чтобы найти класс, который вы используете
0
Xaalek
26 Окт 2020 в 14:13
В Laravel 8 помощник factory
больше не доступен. Класс модели testcase
должен использовать свойство HasFactory, тогда вы можете использовать свою фабрику следующим образом:
testcase::factory()->count(50)->create();
Обратите внимание, что вам также следует обновить вызов фабрики пользователей: factory (‘App User’) -> create () -> id;
Вот соответствующая документация: https://laravel.com/docs/8.x/database- тестирование # create-models
Однако, если вы предпочитаете использовать фабрики стиля Laravel 7.x, вы можете использовать пакет laravel / legacy-factoryies. Вы можете установить его с помощью composer:
composer require laravel/legacy-factories
0
Burhan Kashour
26 Окт 2020 в 14:33
- HowTo
- PHP Howtos
- Call to Undefined Function in PHP
Shraddha Paghdar
Oct 24, 2021
PHP
Many of you have encountered this error several times Fatal error: Call to undefined function function_name()
. In today’s post, we are finding out how to unravel this error. But before we solve this problem, let’s understand how PHP evaluates the functions.
There are several ways to define functions and call them. Let’s say you write it in the function.php file and call it in the main.php file.
// function.php
<?php
namespace fooNamespace {
function foo() {
return "Calling foo"
}
}
?>
// main.php
include function.php
<?php
echo fooNamespacefoo();
?>
Namespaces are qualifiers that enable better management by grouping classes that work together to perform a task. It allows you to use the same name for multiple classes. It is important to know how PHP knows which element of the namespace is required by the code. PHP namespaces work quite a sort of a filesystem. There are 3 ways to access a file in a file system:
- Relative file name such as
fooBar.txt
. It will resolve tofooDirectory/fooBar.txt
where fooDirectory is the directory currently busy directory. - Relative path name such as
subdirectory/fooBar.txt
. It will resolve tofooDirectory/subdirectory/fooBar.txt
. - Absolute path name such as
/main/fooBar.txt
. It will resolve to/main/fooBar.txt
.
Namespaced elements in PHP follow an equivalent principle. For example, a class name can be specified in three ways:
- Unqualified name/Unprefixed class name:Or,If the current namespace is
foonamespace
, it will always resolve tofoonamespacefoo
. If the code is a global, non-namespaced code, this resolves tofoo
. - Qualified name/Prefixed class name:
$a = new fooSubnamespacefoo();
Or,
fooSubnamespacefoo::staticmethod();
If the present namespace is
foonamespace
, it will always resolve tofoonamespacefooSubnamespacefoo
. If the code is global, non-namespaced code, this resolves tofooSubnamespacefoo
. - Fully qualified name/Prefixed name with global prefix operator:
$a = new foonamespacefoo();
Or,
foonamespacefoo::staticmethod();
This always resolves to the literal name laid out in the code,
foonamespacefoo
.
Now suppose you define a class & call the method of a class within the same namespace.
<?php
class foo {
function barFn() {
echo "Hello foo!"
}
function bar() {
barFn();
// interpreter is confused which instance's function is called
$this->barFn();
}
}
$a = new foo();
$a->bar();
?>
$this
pseudo-variable has the methods and properties of the current object. Such a thing is beneficial because it allows you to access all the member variables and methods of the class. Inside the class, it is called $this->functionName()
. Outside of the class, it is called $theclass->functionName()
.
$this
is a reference to a PHP object
the interpreter created for you, which contains an array of variables. If you call $this
inside a normal method in a normal class, $this
returns the object to which this method belongs.
Steps to Resolve the Error of Calling to Undefined Function in PHP
-
Verify that the file exists. Find the PHP file in which the function definition is written.
-
Verify that the file has been included using the
require
(orinclude
) statement for the above file on the page. Check that the path in therequire
/include
is correct. -
Verify that the file name is spelled correctly in the
require
statement. -
Print/echo a word in the included file to ascertain if it has been properly included.
-
Defined a separate function at the end of the file and call it.
-
Check functions are closed properly. (Trace the braces)
-
If you are calling methods of a class, make sure
$this->
is written.
Shraddha is a JavaScript nerd that utilises it for everything from experimenting to assisting individuals and businesses with day-to-day operations and business growth. She is a writer, chef, and computer programmer. As a senior MEAN/MERN stack developer and project manager with more than 4 years of experience in this sector, she now handles multiple projects. She has been producing technical writing for at least a year and a half. She enjoys coming up with fresh, innovative ideas.