How to Test Routes in Laravel: Simple Guide with Examples
In Laravel, you test routes by using the built-in HTTP testing methods like
$this->get() or $this->post() inside your test classes. These methods simulate requests to your routes, and you can assert the response status, content, or redirects to verify the route behavior.Syntax
Laravel provides HTTP testing methods to simulate requests to routes inside test classes. The common methods are:
$this->get('url'): Simulates a GET request.$this->post('url', [data]): Simulates a POST request with optional data.assertStatus(code): Checks the HTTP status code of the response.assertSee(text): Checks if the response contains specific text.assertRedirect(url): Checks if the response redirects to a URL.
These methods are used inside test methods in classes that extend Tests\TestCase.
php
public function test_route_example() { $response = $this->get('/home'); $response->assertStatus(200); $response->assertSee('Welcome'); }
Example
This example shows how to test a GET route /welcome that returns a 200 status and contains the text "Hello, Laravel!".
php
<?php namespace Tests\Feature; use Tests\TestCase; class RouteTest extends TestCase { public function test_welcome_route() { $response = $this->get('/welcome'); $response->assertStatus(200); $response->assertSee('Hello, Laravel!'); } }
Output
OK (1 test, 2 assertions)
Common Pitfalls
Common mistakes when testing routes in Laravel include:
- Not extending the base
TestCaseclass, so HTTP methods are unavailable. - Forgetting to run
php artisan migrate --env=testingto prepare the test database if your route depends on data. - Using incorrect URLs or HTTP methods that don't match the route definition.
- Not checking the correct response status or content, leading to false positives.
Always verify your route exists and matches the HTTP method you test.
php
<?php // Wrong: Using POST on a GET route public function test_wrong_method() { $response = $this->post('/welcome'); $response->assertStatus(405); // Method Not Allowed } // Right: Use GET for the GET route public function test_correct_method() { $response = $this->get('/welcome'); $response->assertStatus(200); }
Quick Reference
Summary tips for testing routes in Laravel:
- Use
$this->get(),$this->post(), etc., to simulate requests. - Assert response status with
assertStatus(). - Check response content with
assertSee()orassertJson(). - Use
assertRedirect()to verify redirects. - Run tests with
php artisan testorvendor/bin/phpunit.
Key Takeaways
Use Laravel's HTTP testing methods like $this->get() and $this->post() to test routes.
Always assert the response status and content to verify route behavior.
Match the HTTP method in your test to the route's method to avoid errors.
Extend the base TestCase class to access Laravel's testing helpers.
Run tests with php artisan test to check your route tests quickly.