logo
podcast Podcast
get help Get Unstuck

Mocking policy logic in a test

Feels like a native Laravel test helper

Joel Clermont
Joel Clermont
2025-01-24

A while ago, I shared an approach I used for testing policy logic. Give that a quick read, if you haven't seen it already.

The thing I like about that approach is that it keeps my feature tests focused on what the controller is doing, but also gives me confidence that the policy logic is wired up correctly.

Friend of the mailing list, Nolan Phillips, took this approach a step further. He created a fake() method which accepts an array of methods and added it to a base Policy class.

Read his brief article here for full context before continuing.

With his approach, now he could do something like this in his tests:

SomePolicy::fake([
    'viewAny' => false,
    'view' => true,
]);

There are two things I like about this:

  1. It feels very much in the spirit of other testing helper's Laravel provides. In fact, I could see Laravel pulling an approach like this right into the framework.
  2. It's a bit easier to read, especially if you have to mock more than one policy method.

I haven't yet used this approach in one of my projects, but I thought it was a clever idea and wanted to share it with you.

Here to help,

Joel

P.S. Testing legacy code can pose challenges, but it can be done! If you need help introducing testing to your legacy project, let's chat.

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.