In this episode, we dive into how to create custom assertions (or 'expectations') in Pest, which can really clean up your repetitive test code. We start by looking at why you'd want a custom expectation in the first place—think about those tests you write over and over, like making sure unauthenticated users are redirected when accessing certain routes. Instead of rewriting the same logic multiple times, Pest lets you encapsulate it in a custom expectation.
We walk through the basics by making a super simple custom expectation that just checks if a value is "Alex". From there, we level up and build something more practical: an expectation to test whether a user gets redirected when accessing a protected route. This new expectation tidies up the test, making it much more readable and easier to write.
We also handle passing in parameters like the URL and optionally the HTTP method. Along the way, you'll see how to access the value inside the custom expectation, use that value (like a user instance), and even chain this with methods like actingAs
to simulate authenticated requests.
Finally, we show how to use this custom expectation on both login and register routes, troubleshoot a failing test, and fix the controller middleware as needed. By the end, you've got a handy new tool for DRY (Don't Repeat Yourself) testing in Pest!