How to test an observer is wired up

If it isn't, then no other logic tests matter

Joel Clermont
Joel Clermont

We don't use observers a lot in our applications, but there are some use cases where they make sense

And I'm a big believer in writing tests to gain confidence in our code. Most test logic is on making sure the listener does what it's supposed to do, but if the observer isn't even wired up, none of those tests will catch it.

I like to write a simple test in my listener test suite to validate that my listener is actually wired up to the model events I expect:

public function testWiredUpSuccessfully(): void

        sprintf("eloquent.created: %s", Client::class),
        sprintf('%s@created', ClientObserver::class)

It's quick to write, clear to read, and will catch if you fail to wire up the observer correctly.

Here to help,


P.S. You are writing tests for your Laravel app, right? If not, let's talk.

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.