Elequent Factories
Tests
Eloquent Factory classes SHOULD be used only for tests. In the application context, Model methods, Actions and Services SHOULD be used instead.
To even more separate "application" and "test" contexts, please:
- keep all factories at the
database/Factoriesdirectory (Database\Factoriesnamespace) - Must use
HasFactorytrait in Model classes - in tests, call Factory classes directly:
$user = UserFactory::new()->create([...]);
Factory::definition() should not set any state or set a default state only
For Models that have finite number of states (Finite-state machine, e.g. Article can be one of draft, published, archiced states), the Factory::definition method SHOULD NOT make a Model of any non-default state: the state should be set explicitly in the test.
For cases, when the state is not important, the recommendation is to create a method alias that underlines this (see ofAnyValidState):
PHP
final class ArticleFactory extends Factory
{
/** @inheritDoc */
public function definition(): array
{
return [
'title' => fake()->sentence,
'body' => fake()->paragraph,
];
}
public function draft(): self
{
return $this->state(['published_at' => null]);
}
public function published(): self
{
return $this->state([
'published_at' => today(),
'meta_description' => fake()->sentence,
]);
}
public function ofAnyValidState(): self
{
return $this->draft(); // or even return a random valid state
}
}
