Black Friday: the Laravel testing course is $149 instead of $249, through Dec 7. See the course →
logo

Default factories should do as little as possible

Another time laziness pays off

Joel Clermont
Joel Clermont
2024-09-19

From our daily Laravel tips email. Get the next one in your inbox.

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.

Want a tip like this in your inbox every weekday?

Each one takes less than 2 minutes to read. Join 4,000+ Laravel developers who already get them.

email
No spam. Only real-world advice.
Toss a coin in the jar if you found this helpful.