Courses

Testing in Laravel 11: Advanced Level

Follow Redirects and Test Final Result

Summary of this lesson:
- Test HTTP requests with redirects
- Follow redirects in test requests
- Check final response after redirection
- Verify page content and database state
- Combine multiple assertions in a single test

If you are testing a case of posting the form and then redirecting somewhere, a typical approach is to perform the POST request, assert the status redirect to "somewhere", and then check the database.

use function Pest\Laravel\actingAs;
 
test('created product exists in the database', function () {
actingAs($this->user)
->post('/products', [
'name' => 'new product',
'price' => 100,
])
->assertRedirect('/products');
 
$this->assertDatabaseHas('products', [
'name' => 'new product',
]);
});

But this test doesn't check what happens on that resulting /products page after that.

The good news is that it is possible to trace the redirect!


In this example, before actingAs(), we must add the followingRedirects().

Then, instead of asserting redirect, we assert...

The full lesson is only for Premium Members.
Want to access all 31 lessons of this course? (74 min read)

You also get:

  • 69 courses (majority in latest Laravel 11)
  • Premium tutorials
  • Access to repositories
  • Private Discord