Back to Course |
Testing in Laravel 11: Advanced Level

Follow Redirects and Test Final Result

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 status 200 with assertOk(), because now we're working with the final destination of our request, the /products page.

Then, we can assert that the desired text is seen on the page. Of course, we also check if the record is in the database.

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

So, this is a double-check and double-test. We test that the product is visible on the final page and exists in the database.