DEV Community

Recca Tsai
Recca Tsai

Posted on • Originally published at recca0120.github.io

Laravel Testing: Assert Final Page Content After a Redirect

Originally published at recca0120.github.io

Scenario

A controller creates data and then redirects:

class UserController extends Controller {
    public function create(Request $request) {
        $user = User::create($request->all());

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

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

class UserControllerTest extends TestCase {
    public function test_it_should_show_user_after_create_user() {
        $this
            ->followingRedirects()
            ->post('user', [
                'name' => 'foo'
            ]);
    }
}
Enter fullscreen mode Exit fullscreen mode

Laravel < 5.4.12

In older versions, the method name drops the "ing":

$this->followRedirects()->post('user', ['name' => 'foo']);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)