1

I'm trying to write some Laravel factories so that we can seed all tables upfront and also use them for tests.

I'm not very experienced with testing and I have some doubts on which premises should factories be built.

Let's use this simple example, 2 tables:

  • users
  • notes

Notes have a user_id field with a FK.

Should I make the notes factory to be able to create users (calling users factory) or expect that in any test that I try to create notes I have already created users that can be associated with the notes?

Please give some practical example if you may.

Johny Serpa
  • 155
  • 1
  • 2
  • 16
  • Could you have your Note Factory pull a random user from the database and assign a `user_id` based on that? – Tim Lewis Apr 23 '18 at 17:07
  • I've found it useful to include automatic creation of related models within the factory definition. Simply because it often saves you from writing additional code. And when you need to attach it to a specific model you can do that on the go: `factory(Model::class)->create(['related_id' => $related->id])`. As for tests, I think it's best to create the data within the test, otherwise you can quickly lose track of what data you already have and should expect. As for this question, it's primarily opinion based and not the best fit for Stack Overflow. – DevK Apr 23 '18 at 17:08
  • @TimLewis yes I can. That was my solution for now to do it as you say. Wondering if it is a good practice or a limited one. – Johny Serpa Apr 23 '18 at 17:37
  • Hard to say really; my usage of Factories is pretty limited, but I feel like *creating* Users in a Note Factory is somewhat backwards. Pulling them from the database, choosing one at random and attaching a Note to it sounds like it would work. – Tim Lewis Apr 23 '18 at 17:49

1 Answers1

0

Relationship while seeding can be done. Try this code in your NoteFactory.

'user_id' => function(){
      return App\User::all()->random();
}

Note that your UserFactory should run first and then NoteFactory.

aj3sh
  • 366
  • 3
  • 10