Reputation: 528
I'm trying to test my app using testing in laravel. But I have an error, whenever I run the test using php artisan test it always say Unable to locate factory for [App\Models\User]
. I can't figured out why this is happening
here is my test code:
<?php
namespace Tests\Feature;
use Tests\TestCase;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
class Fish extends TestCase
{
/** @test */
public function test_authenticated_users_can_access_home()
{
$user = factory(User::class)->create();
$this->actingAs($user);
$response = $this->get('/home')->assertOk();
}
}
and this is my model:
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasFactory, Notifiable;
...
UserFactory
<?php
namespace Database\Factories;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
class UserFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = User::class;
/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
return [
'name' => $this->faker->name(),
'email' => $this->faker->unique()->safeEmail(),
'email_verified_at' => now(),
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
'remember_token' => Str::random(10),
];
}
...
}
any help would be very appreciated, thank you sorry for my bad english
Upvotes: 2
Views: 660
Reputation: 1336
From your UserFactory class, I assume you are using Laravel 8.
The new way to call factories in Laravel 8 is
$user = User::factory()->create();
instead of the old way
$user = factory(User::class)->create();
I think you mixed Laravel 8 and 7 syntax in your ProjectFactory. I would recommend to delete your ProjectFactory and recreate it on Laravel 8 basis with the PHP artisan command: php artisan make:factory ProjectFactory
. Then you would call the factory like this:
$project = Project::factory()->create();
Make sure your Project model uses the hasFactory; trait for this to work.
Upvotes: 2