In this episode, we focus on improving our Pest test suite by introducing more custom expectations to tidy up our test code. We notice that certain authentication checks are popping up all over our tests, which can make things repetitive and less readable. So, we set out to create a custom expectation that lets us easily assert whether a guest user is redirected, making our tests more expressive and maintainable.
We walk through the process of refactoring a test for unauthenticated (guest) users, aiming for a syntax like expect_guest()->toBeRedirectedFor('books.store')
. This would hide the implementation details and provide a smoother, more fluent way to express our intent. We encounter some typical issues, such as Pest expecting a user object, and solve them by customizing the helper to pass null
and handle that scenario gracefully. This little hack shows just how flexible Pest can be when you want to streamline your tests.
After setting up the helper and ensuring it works for both authenticated and guest flows, we run our tests to make sure nothing broke. Everything passes, our tests read a lot better, and we've got a reusable pattern that's handy across multiple parts of the app. It's a small refactor, but it goes a long way in making repeated test scenarios much easier to write and read.