I started building a web application using Laravel 8. I have noticed that a couple of things have changed in the Laravel 8 including model factory. Now, I am writing a unit test using factories for models. But it is throwing error when I fake the fields using faker.
This is my test method.
public function testHasRoleReturnsTrue()
{
$user = User::factory()->create();
}
As you can see, all I am trying to do right now is that I am trying to create a user using factory. This is my factory class for user model.
<?php
namespace Database\Factories;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Foundation\Testing\WithFaker;
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),
];
}
}
As you can see I am faking values using faker. When I run the test, I got the following error.
InvalidArgumentException: Unknown formatter "name"
/var/www/vendor/fzaninotto/faker/src/Faker/Generator.php:248
/var/www/vendor/fzaninotto/faker/src/Faker/Generator.php:228
/var/www/vendor/fzaninotto/faker/src/Faker/Generator.php:274
/var/www/database/factories/UserFactory.php:28
/var/www/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/Factory.php:366
/var/www/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/Factory.php:345
/var/www/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/Factory.php:329
/var/www/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/GuardsAttributes.php:157
/var/www/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/Factory.php:334
/var/www/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/Factory.php:302
/var/www/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/Factory.php:228
I assume that the error is because I am using faker. But I cannot spot any issue in the code. What is wrong with my code and how can I fix it?
It's because you are using this in Unit tests. And it is extending PhpUnit's TestCase.
When you extend Laravel's TestCase it should work.