Featured image of post Laravel Testing: Assert Final Page Content After a Redirect

Laravel Testing: Assert Final Page Content After a Redirect

POST requests only return a 302, hiding the final page. Use followingRedirects() to automatically follow redirects and assert on the destination page content.

Scenario

A controller creates data and then redirects:

1
2
3
4
5
6
7
class UserController extends Controller {
    public function create(Request $request) {
        $user = User::create($request->all());

        return redirect(uri('users.show', ['id' => $user->id]));
    }
}

When writing tests, you want to verify the content of the page after the redirect, but $this->post(...) only returns a 302 response – you can’t see the final page.

Solution

Add followingRedirects() to make the test automatically follow the redirect:

Laravel >= 5.5.19

1
2
3
4
5
6
7
8
9
class UserControllerTest extends TestCase {
    public function test_it_should_show_user_after_create_user() {
        $this
            ->followingRedirects()
            ->post('user', [
                'name' => 'foo'
            ]);
    }
}

Laravel < 5.4.12

In older versions, the method name drops the “ing”:

1
$this->followRedirects()->post('user', ['name' => 'foo']);