Summer Sale! All accounts are 50% off this week.

liandhas's avatar

Unknown formatter "name"

I have an error while testing. Below are the code and error.

`public function definition() {

    return [
        'name' => $name = $this->faker->title,
        'slug' => Str::slug($name),
        'description' => $this->faker->paragraph,
        'price' => 1000
    ];

}

at C:\xampp\htdocs\Projects\apiMB\vendor\fzaninotto\faker\src\Faker\Generator.php:248 244▕ 245▕ return $this->formatters[$formatter]; 246▕ } 247▕ } ➜ 248▕ throw new \InvalidArgumentException(sprintf('Unknown formatter "%s"', $formatter)); 249▕ } 250▕ 251▕ /** 252▕ * Replaces tokens ('{{ tokenName }}') with the result from the token method call

1 C:\xampp\htdocs\Projects\apiMB\vendor\fzaninotto\faker\src\Faker\Generator.php:228 Faker\Generator::getFormatter("name")

2 C:\xampp\htdocs\Projects\apiMB\vendor\fzaninotto\faker\src\Faker\Generator.php:285 Faker\Generator::format("name", [])`

0 likes
9 replies
automica's avatar

@lianmaymesi probably best to do this:

   $name = $this->faker->title;

    return [
        'name' => $name,
        'slug' => Str::slug($name),
        'description' => $this->faker->paragraph,
        'price' => 1000
    ];
liandhas's avatar
$name = $this->faker->title;

return [
	'name' => $name,
	'slug' => Str::slug($name),
	'description' => $this->faker->paragraph,
	'price' => 1000
];

Still, the error is the same, Unknown formatter "title"

laracoft's avatar

@lianmaymesi

try

$name = $this->faker->name;

return [
	'name' => $name,
	'slug' => Str::slug($name),
	'description' => $this->faker->paragraph,
	'price' => 1000
];
Marcoonsiglio's avatar

I found that using factory in a setUp() method trigger this error. The error disappear if I move the setUp() code in the test method.

Marcoonsiglio's avatar

Yuppie!!! I solved it!

Solution 1

Use factories in setUp() method but remove the WithFaker trait.

Solution 2

Use factories in test method but not in setUp() method having care to use WithFaker trait.

P.S. Have care to use

parent::setUp();

in your setUp() method.

7 likes
kilimanjaare's avatar

Using laravel 8 migrations requires you to:

  1. Use TestCase as a parent class
  2. Override withFaker() method (Illuminate\Database\Eloquent\Factories\Factory)

You can try next solution inside your faker class:

protected function withFaker()
{
   return \Faker\Factory::create('en');
}
2 likes
vigorexa's avatar

In tests you have to call parent::setUp(); before your faker generation

use CreatesApplication, RefreshDatabase;

protected function setUp(): void
{
    parent::setUp();
    $this->user = UserFactory::new()->create();
}

Laravel v9.0

1 like

Please or to participate in this conversation.