Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: Call to undefined function Tests\factory()

Tags:

php

laravel

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 command phpunit --filter testUserCanCreateItem I get the following error:

Error: Call to undefined function Tests\factory()

No idea what is causing it. I have looked at my factories and my testcase.php but I could not find a solution. What am I doing wrong?

My testcase.php:

<?php

namespace Tests;

use Illuminate\Foundation\Testing\TestCase 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

like image 692
Parsa_237 Avatar asked Dec 11 '22 00:12

Parsa_237


1 Answers

In Laravel 8, the factory helper is no longer available. Your testcase 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('App\User')->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
like image 50
Burhan Kashour Avatar answered Dec 13 '22 23:12

Burhan Kashour