mercredi 5 décembre 2018

Different factory parameters for testing environment

My current factory creates posts and assigns a random user_id from existing users which are seeded before. But in the testing environment sometimes I need to created just thread without user and I receive an exception:

1) Tests\Feature\CreateThreadsTest::guests_may_not_create_threads
InvalidArgumentException: You requested 1 items, but there are only 0 items available.

This is my factory for seeding the database:

$factory->define(
    App\Models\Thread::class, function (Faker $faker) {
        return [
        'user_id' => \App\Models\User::pluck('id')->random(),
        'title' => $faker->sentence,
        'body' => $faker->paragraph
        ];    
    }
);

How can I change it only for testing environment to:

'user_id' => function () {
            return factory('App\Models\User')->create()->id;
        },

Aucun commentaire:

Enregistrer un commentaire