Ensure all routes in your laravel app are working
In any web app, ensuring all your routes are available and not returning errors is crucial. Dedicated route tests are the way to go here, but we don’t always have a fully covered codebase. And let’s be honest, we’re not manually going through all routes before each deploy to ensure we didn’t break anything.
To help with this, a PestPHP plugin package called spatie/pest-plugin-route-testing is made, which adds a basic layer of coverage.
Let’s go through it. Let's start by adding a file to your test directory.
<?php namespace Tests; use function Spatie\RouteTesting\routeTesting; it('can access all GET routes of the Api', function () { routeTesting() ->including(['/api/*']) ->bind('post', Post::factory()->create()) ->bind('comment', Comment::factory()->create()) ->assert(function(Response $response) { // perform custom assertions }) ->toReturnSuccessfulResponse();});
This simple test will ensure that all GET routes in your application return a 200 HTTP code or a redirect.
Route model binding
In case you are using route model binding, you can pass on a model with bind
.
routeTesting() ->bind('post', Post::factory()->create()) ->toReturnSuccessfulResponse();
By default, routes with unknown bindings are ignored. The debug option can be handy for this!
Debugging
The debug
option provides additional insights during the testing process, such as the number of routes covered and missing route model bindings.
routeTesting() ->debug() ->toReturnSuccessfulResponse();
CLI output would look like this:
Excluding routes
Sometimes, you may want to exclude specific routes from being tested. This can be done using the excluding
method.
routeTesting() ->excluding(['/webhooks/stripe'])
You can also use wildcards to exclude a group of routes:
routeTesting() ->excluding(['/webhooks/*'])
By default, the package ignores routes like _ignition
and horizon*
.
Including routes
Including routes work the same as excluding. You can combine both with a wildcard.
Custom assertions
Add custom assertions for specific routes using the assert
method:
use Illuminate\Testing\TestResponse; routeTesting() ->including('api/*') ->assert(function (TestResponse $response) { $response->assertStatus(201); }) ->toReturnSuccessfulResponse();
In closing
We've made this package for our own needs and packaged it, so you don't have to code it up in your project. You can see a list of all packages we've made on our company website.