logo

Think before changing application code for tests

There might be a better option

Joel Clermont
Joel Clermont
2026-01-29

I was reviewing a PR where a test was failing. A user without a role was causing an error in the authorization logic.

The application never expected that situation and was throwing an exception.

My first proposed fix was to add a check to gracefully handle any user without a role.

But wait! In our application, a user should never be without a role.

This is by design. Every user gets a default role on creation.

It's true that adding that check would have made the test pass, but that's the wrong issue to fix.

The problem was that our data was set up wrong in the test, so that's what we should fix:

public function testNonAdminCannotAccessDashboard(): void
{
    $user = User::factory()->create();
    $user->assignRole('viewer');  // Add this role, problem solved

    $this->assertFalse($user->canAccessDashboard());
}

The test now reflects reality.

The lesson? Be careful when you catch yourself modifying application code purely to make your tests pass. Sometimes the test is telling you something is wrong with your test, not your app.

Here to help,

Joel

P.S. Did you know we publish these tips in a volume for easy offline reading?

Toss a coin in the jar if you found this helpful.
Whack a Joel
Score:
Not a Winner!
joel Score:
What is this?

Aaron was bored. Joel was there. Play the game!

Want a tip like this in your inbox every weekday? Sign up below 👇🏼
email
No spam. Only real-world advice.