BLOG // May 14, 2021

Laravel automatically test all your public URLs in PHPUnit

Below is a nifty little piece of code to include in your Laravel unit tests in order to check for any random 500 errors in all your public pages.

It often catches a side-effect of a change causing issues on a page, etc. Especially as a dynamic site grows.

I recommend it in additional to all your normal tests, not as a replacement. It also obviously only crawls pages that match the following criteria:

  • Public pages
  • GET requests
  • No parameters required

On LoadForge many of our public pages are dynamic - giving outputs of the number of tests run, getting pricing info from the database, reading markdown parsed examples, etc. This serves as a great catchall for any potential issues.

public function testAllPublicPages()
{
    $routes = Route::getRoutes()->getRoutesByMethod()['GET'];

    foreach ($routes as $route) {
        // Ignore routes that require options
        if (strpos($route->uri(), '{') !== false) {
            continue;
        }

        // Ignore authentication routes
        if (in_array('auth', $route->middleware(), true)) {
            continue;
        }

        // Only target controllers in the right namespace
        if (isset($route->action['controller']) && strpos($route->action['uses'], 'App\\Http\\Controllers') === false) {
            continue;
        }

        // Ignore API routes
        if (strpos($route->uri(), 'api') !== false) {
            continue;
        }

        $response = $this->get($route->uri());
        $response->assertStatus(200);
    }
}

Comments

Subscribe to new articles

If you enjoy my content, consider subscribing. You will only receive new blog stories, no other email.