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?
- Consistency - this leads to less flaky tests or surprising test behavior
- Readability - using named states for additional setup makes the test more readable
- 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.