A good rule for when to create a factory state

Make your tests more readable

Joel Clermont
Joel Clermont

Some of the data we generate in our database factories is just for display purposes. For example, when generating a bunch of users, we don't really care what random names are generated.

On the other hand, some fields will impact the business logic of our application. For example, we may have different types of addresses (work, home, school), but only certain types of users have access to each type of address. This will affect validation rules, what is rendered in the UI, and maybe other logic too.

In a case like this, I will create named factory states for each value. Using my above example, I'd create three states in my AddressFactory named work(), home(), and school(), and all those states would do is set that one value.

If the field is non-null in your database schema, you'll need to pick one of those values for the default factory state, but I will still also create a named state with the same value. It makes the tests much easier to read and understand.

Here to help,


P.S. Would you like a deeper understanding of how Laravel validation works and how to use it effectively in your app?

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼

Level up your Laravel skills!

Each 2-minute email has real-world advice you can use.