Adding a random function to factories #36289
Replies: 2 comments 2 replies
-
I've actually been trying to take randomness out of my tests. Randomness could give a fall sense of security if your tests are green, but never actually hitting the random event that causes them to fail. IMO, if you truly need to test a condition, be explicit and test it. And there's nothing more frustrating than a test that passes on some runs, and fails on others. I've recently just removed all the I'd almost be more interested in being able to explicitly make one User with 0 posts, one User with 1 post, and one User with 2 posts. |
Beta Was this translation helpful? Give feedback.
-
Late to the party. Pull Request ist open #49637. This solves this. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Is there any interest in adding a random function to factories?
User::factory()->rand(0, 3)->create();
I can create a PR if this is approved.
The use case would be for creating related models with a factory.
Passing rand() into the count method generates the same number of items for each,
where this would allow for a random number of items.
Same number of post for every user :
$user = User::factory()->count(3)->has(Post::factory()->count(rand(0, 3)))->create();
Random number of posts for each user :
$user = User::factory()->count(3)->has(Post::factory()->rand(0, 3))->create();
Possible implementation :
/**
* Specify a random number of models to be generated.
*
* @param int $min
* @param int $max
* @return static
*/
public function rand(int $min, int $max)
{
return $this->newInstance(['count' => rand($min, $max)]);
}
Beta Was this translation helpful? Give feedback.
All reactions