Parsa_237
Parsa_237

Reputation: 127

Error: Call to undefined function Tests\factory()

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

Upvotes: 7

Views: 11900

Answers (4)

Julker Nien Akib
Julker Nien Akib

Reputation: 65

First run this command composer require laravel/legacy-factories

public function YourMethodName()
    {
        $user = factory(User::class)->create();
        $this->actingAs($user);

        //code...
    }

Upvotes: -1

Parsa_237
Parsa_237

Reputation: 127

Guys I found the solution to my answer.

I needed to add the model name in my AssortmentFactory. So I did:

protected $model = Assortment::class;

and I also needed to import the model by doing use App/Models/Assortment.

In the UserFactory I also needed to import the model by doing App/Models/Assortment.

This solved my issue.

Upvotes: 1

Burhan Kashour
Burhan Kashour

Reputation: 677

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

Upvotes: 15

Elie
Elie

Reputation: 142

You may have to specify that you are using an other class.

Did you write use Assortment or use \Assortment above ?

You can also use the manager to find the class you are using

Upvotes: 0

Related Questions