HardDrive's avatar

Create just one related model for feature test

If I am writing a test that contains both a user model and a post model each has an associated Model Factory. I know I can do the following to create a collection of related records but how do I create just one of each for use during a feature test.

$users = factory(App\User::class, 3)
           ->create()
           ->each(function ($u) {
                $u->posts()->save(factory(App\Post::class)->make());
            });

for example

$customer = factory('App\User')->create()

// then add a single post to this user

Many Thanks

0 likes
3 replies
goatshark's avatar

@rossuk I'm not completely clear on what you mean by "create just one of each for use during a test", but here is one approach I've used:

$customer = factory('App\User')->create();
$post = factory(App\Post::class)->make(['customer_id' => null]);
$new_post = $customer->posts()->create($post->toArray());

Alternatively, if your PostFactory automatically creates a user when it creates a post, one could just create three posts via the factory and they would each have their own user.

1 like
tykus's avatar
tykus
Best Answer
Level 104

No need to use the relationship, you can pass attributes to the create or make factory methods:

$customer = factory('App\User')->create();
$post = factory(App\Post::class)->create(['customer_id' => $customer->id]);
1 like

Please or to participate in this conversation.