logo

A deeper dive into how Laravel Auditing works during tests

How I kept my test assertions clean

Joel Clermont
Joel Clermont
2025-11-24

I previously discussed an issue I bumped into trying to write tests against records created by the Laravel Auditing package.

After solving that issue, I ran into something else that I wanted to share.

One of my tests required me to create a handful of models. Only one of these had encrypted fields, but all had auditing enabled.

The logic I was trying to test was specifically on the audit record from when I later called save() to edit that encrypted model.

To simplify my assertions, I thought I would just move the line which enabled the auditing config in the test environment until just before I called save(). This way I'd only have one audit record for the model I was editing, simplifying my test logic.

But when I did this, no audit was produced at all.

Why? The auditing package only registers its observer when the model first boots.

So by leaving auditing disabled earlier in my test setup when I called the factories, even if I turn auditing on later, those models would never be wired up to listen for events to audit.

I briefly considered using createQuietly on the factories to avoid generating audit records during test setup, but that wouldn't work because I needed other model events to fire.

In the end, my solution was simple: I kept my line to enable auditing at the start of the test, let the events fire, and let the audits get created, but then I just deleted all audit records right before making my edit.

This still left me with a pristine audit history, keeping my assertions nice and clean.

And for good measure, I added a simple comment above the audit deletion to explain why I was doing it.

Here to help,

Joel

P.S. Would you like to learn more about how to write effective tests in your Laravel app?

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.