logo
podcast Podcast
get help Get Unstuck

Get more specific when asserting events dispatched

More confidence and better errors

Joel Clermont
Joel Clermont
2024-08-07

Laravel offers so many excellent test helpers that let you write expressive tests with minimal effort.

For example, you can use Event::assertDispatched in a feature test to assert that a specific event was dispatched.

This method allows you to just specify the event name, but you can go a step further and provide a callback to make additional assertions about the event:

Event::assertDispatched(OrderShipped::class, function (OrderShipped $event) use ($user) {
    self::assertTrue($event->order->customer->is($user));
    self::assertEquals(100, $event->order->total);
    // more assertions here...
    
    return true;
});

Sometimes I see projects using this callback, but chaining a bunch of tests together into a single boolean value that gets returned.

While this works, it can be hard to debug when the test fails. You won't know which specific assertion failed, just that one of them did.

Instead, I like the approach shown above where you make individual assertions and return true at the end. Then, if you get a failure, you immediately know which specific piece of logic is broken.

Here to help,

Joel

P.S. Do you have flaky, slow, or brittle tests? We have a ton of experience fixing these issues and getting more value out of your test suite. Give us a call!

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼
email
No spam. Only real-world advice you can use.