In this episode, we're exploring how to write cleaner, higher-order tests using Pest (and Laravel). We try to rewrite an existing test by chaining all the assertion methods together for a more elegant, fluent approach. However, we quickly hit a snag: methods like assertDatabaseHas
can't just be chained onto the response object, because they're not available on that class.
We dig into the reason by looking at what is actually returned when we call post()
—it's a TestResponse
, which does let us chain response-related assertions, but not global ones like checking the database or authentication status. To get around this, we demo how to use Laravel's tap()
helper function. This lets us do all our response assertions within the closure, and then outside, we can continue chaining methods like assertDatabaseHas
and assertAuthenticated
directly on the test context.
By the end, we refactor the test to be much cleaner and discuss a few shorthand approaches for even more concise code. The result: more readable, maintainable higher-order tests that still let you check everything you need—whether it's the response, the database, or the authentication state.
So, you'll come away understanding how to properly "tap into" your tests, mix chaining with global assertions, and generally make your test suite more elegant and fun to work with!