canfone's avatar

How do I test a view file after redirect?

Hello,

I created a test when logging out, it will redirect with the login page with a message on it. I am trying to create a feature test for this but it seems Laravel doesn't have a follow redirect feature so I can test and see if my message was asserted. Here is my code.

This is my logout function. As you can see, I have a redirect after successfully logout with a message on it.

    /**
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function logout(Request $request)
    {
        Auth::guard()->logout();
        $request->session()->flush();
        $request->session()->regenerate();

        return redirect('/account/login')
            ->withMessage([
                'type' => 'success',
                'text' => trans('text.account.logout.message')
            ]);;
    }

Then here is my test function.

    public function testGetLogout()
    {
        $response = $this->get('/account/logout');
        $response->assertStatus(302);
        $response->assertRedirect('/account/login');
        $response->assertSee("Thank you for using GetDonations, we would like to see you more in the future.");
    }

This line will fail because it's checking if the text is in the /account/logout route but the text is displayed in /account/login route. I don't know how can I assert in the newly redirected route.

$response->assertSee("Thank you for using GetDonations, we would like to see you more in the future.");

If anyone can help me with this small problem that should be amazing.

Thanks!

0 likes
4 replies
AR's avatar

You need to be logged in as a user first. And then access the link and after that assert that the page is login and assert that you see the message.

1 like
EventFellows's avatar

You should change the last 2 $response->assertSee to $this->assertSee as it is not related to the response but a new request after the redirect.

adamwathan's avatar
Level 6

Rather than asserting that the text is visible on the page, I would just assert that the text is present in the session:

$response->assertSessionHas('message', [
    'type' => 'success',
    'text' => "Thank you for using GetDonations, we would like to see you more in the future."
]);

If you want to follow the redirect, you'd need to switch back to the old BrowserKit testing package or use Dusk.

5 likes

Please or to participate in this conversation.