Back to Course |
Testing in Laravel 11 For Beginners

Important: Test "Happy" and "Sad" Paths

The final part of this "philosophical" course section on "what to test" is about the happy/unhappy paths. The example is from our tests.

test('admin can see products create button', function () {
$admin = User::factory()->create(['is_admin' => true]);
 
actingAs($admin)
->get('/products')
->assertStatus(200)
->assertSee('Add new product');
});
 
test('non admin cannot see products create button', function () {
actingAs($this->user)
->get('/products')
->assertStatus(200)
->assertDontSee('Add new product');
});

For example, we covered the create button for products in previous lessons.

I added two tests for the opposite cases:

  • The "happy path": if I'm an admin, I can see the button
  • The "non-happy path": if I'm not an admin, I cannot see the products create button.

And this is important.

Quite often, I see people writing tests only for the happy path. For example, they test if the page loads successfully with some ideal parameters. They don't cover the failures, the exceptions, or cases when something can go wrong.

But that kind of defeats the whole purpose of testing. We need to think like our users and come up with scenarios that would break our applications. What can really go wrong?

  • What if some user input is invalid?
  • What if some URL is invalid?
  • What if someone loads some page without access?
  • What if a crucial DB record is deleted?
  • etc.

How does your page/application behave, then? Does it throw an Exception? Does it show a helpful error message on the screen? Does it return the correct HTTP status code?

So, that's why I always recommend testing the failure scenario first. Then, your brain automatically starts to think about what can go wrong. It naturally gets triggered with more ideas for more scenarios, and then the happy path becomes the easier part of testing. Because, by then, you would cover all the failure scenarios.

So, the "unhappy path" part of writing tests takes most of the time, and then we come back to the same question: what if you don't have enough time to test all the scenarios? Then, again, it becomes your personal decision. How much risk do you want to take by not covering some specific scenarios? What are the probabilities of that to happen?

Some scenarios are edge-edge cases; you should spend less time on those. That's your personal choice, depending on how much time you have. But, my main point of this lesson is this: remember to cover both the happy and unhappy paths.