Use factories to make your tests more readable

Only include relevant details in your test setup

Joel Clermont
Joel Clermont
2024-01-03

Tests are great for making sure code works as expected, but a well-crafted test suite can also help developers understand how a feature is supposed to work. It becomes living documentation.

But in order for tests to serve that purpose well, it's important to make the tests as readable as possible. One way to do this is by removing irrelevant details in the test setup.

For example, if I need a trashed record, instead of passing deleted_at with a specific date time value into the factory's create() method, I prefer to use the trashed() factory state.

// Why is this specific date here? Is it relevant to what I'm testing?
$user1 = User::factory()->create(['deleted_at' => '2023-01-15 12:45:00']);

// Much better! I just need a soft-deleted User, the date does not matter
$user2 = User::factory()->trashed()->create();

If the specific date a record was trashed is not relevant to the test, then don't include it. It keeps the focus on what is actually important in the test setup.

And if the date is important to the test logic, you can then pass it in instead of using the factory state. You retain flexibility in your test setup, and keep the test as focused as possible.

Here to help,

Joel

P.S. I talk about testing a lot because I find it incredibly valuable. In fact, when we join a project testing is non-negotiable. Read more about how we work!

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.