logo
podcast Podcast
get help Get Unstuck

Default factories should do as little as possible

Another time laziness pays off

Joel Clermont
Joel Clermont
2024-09-19

I have found it very helpful to have my default factory state do as little work as possible.

What does that mean? At a base level, if a field is nullable in the database schema, I don't set it in the default factory state.

But even beyond that, I try not to get too fancy with the setup. Let's say a required field can have one of three different values. I just pick one and make that the default. I don't randomly pick one, especially if it drives business logic.

Then, you can create additional factory states with meaningful names for the other values, or for optional fields and relationships.

Why do I find this approach helpful?

  1. Consistency - this leads to less flaky tests or surprising test behavior
  2. Readability - using named states for additional setup makes the test more readable
  3. Speed - the less work the factory has to do, the faster your tests will run, especially if you have optional relationships

Here to help,

Joel

P.S. Keeping things simple not only helps our code run faster, but keeps the team running faster too. It's one of the reasons we're so productive when working with Laravel teams.

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼
email
No spam. Only real-world advice you can use.