Reputation: 41
I want to generate the same data every time with already existing Laravel (5.7) factories. I saw that Faker does have an option to set seed - $faker->seed(123);
, but this have to be added to every single factory.
I was looking for a way to do this, but without success. The $faker
is set in the constructor of the Factory class, and I thought I can just extend it and add the seed method to $faker
. The problem is this class is used in the helpers.php (line 495)
which is vendor file, that cannot be modified. Is there maybe a way to overwrite those helper functions in Laravel? Or maybe there is a easier way, that I'm not seeing.
Upvotes: 4
Views: 961
Reputation: 11
For anyone looking for more recent version:
public function setUp(): void
{
parent::setUp();
app(\Faker\Generator::class)->seed(919237);
}
Our use-case was making tests deterministic while keeping seeders random.
Upvotes: 1
Reputation: 41
The \Illuminate\Database\Eloquent\Factory
class has an extra static constructor which allows you to pass your own instance of faker in and then loads your existing factories as normal. You can use it as follows:
$faker = \Faker\Factory::create();
$faker->seed(1234);
$factory = \Illuminate\Database\Eloquent\Factory::construct($faker);
// Then use the factory as follows
$user = $factory->of(\App\User::class)->create();
If you need to use the seeded factory in multiple places across your test base, I'd recommend binding it to the container in your setUp()
method.
Upvotes: 3
Reputation: 676
Faker will need to seed only if you notice that you will get some duplicate results all the time. If not i do not think it is even required to set the seed itself
Upvotes: 0