In this episode, we're diving into how to test individual query filters in a Laravel application. Instead of running full feature or browser-based tests, we're focusing on crafting integration-level tests for each filter, which are a nice balance between unit and feature tests.
We start off by preparing our testing environment—switching the database config to SQLite in-memory (so tests don't mess with real data) and cleaning out the example tests Laravel gives us by default. With the slate clean, we create a new feature test specifically for our UnsolvedQueryFilter
.
Since we need some fake data for the tests, we set up a factory for our Discussion model and use Laravel's factory features to make two discussions: one that's marked as solved and another that's not. This gives us a realistic test scenario.
The test then uses our filter class and simulates what it would do on a real query. We run into a little issue with the next
parameter (needed by the filter's handle method), but we work around it by passing a simple anonymous function. Finally, we assert that only one discussion is returned when we apply the "unsolved" filter—just as we expect.
The key takeaway here: these filter tests are straightforward once you set up your data, and you can copy this approach for different filters in your project. It's a great way to keep your logic solid, quick, and easy to maintain!