oikodomo's avatar

Assert Redirected/Current-Route and View

I want to assert where i end up after the redirect and what the resulting view contains. I started with the request:

$response = $this->actingAs($user)->get('/...');

then I assert the redirect

$response->assertRedirectToRoute(...)

and then I want to assert if the view where I was redirected contains a specific value

$response->assertViewHas(...)

But in this case I ended up with the message: The response is not a view. I got this to work with the "followingRedirects" method

$this->followingRedirects()->actingAs....

but then i couldn't assert where I was redirected. I get the message

Expected response status code [201, 301, 302, 303, 307, 308] but received 200.
Failed asserting that false is true.

Is there a way to do both? I dont need to test if it was a redirect. if there is an assert-method to check the current route of a response after "followingRedirect" then I would use that too.

0 likes
5 replies
s4muel's avatar
s4muel
Best Answer
Level 50

i think you cant do both at a time, IMHO with followingRedirects() it just does a get request until there is no redirection anymore and you dont have access to the previous request headers to assert on.

if really necessary i would split the test into two:

it_redirects_to...()
{
    //do not use followingRedirects() here and check assertRedirectToRoute()
}

it_contains_..._on_the_redirect_page()
{
    //use followingRedirects() and use assertViewHas()
}
1 like
oikodomo's avatar

@s4muel Damn, I hope not. :/ I currently do exactly that as a workaround. Thank you for the help.

1 like
s4muel's avatar

@oikodomo well, it really seems to be exactly like that, just a while loop to go through all redirects: https://github.com/laravel/framework/blob/10.x/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php#L694

if checking the view is not enough for your test - i mean without checking the redirection. i suppose without the redirection, the view doesn't have the right data anyway, right? or even you get totally different view? i really would stick to two separate tests and wouldn't make a big deal out of it.

2 likes
oikodomo's avatar

I also tried assertLocation

$response = $this->followingRedirects()->.....
$response->assertLocation(...)  //<= instead of assertRedirect
$response->assertViewHas(...)

but interestingly the location in the header is only set without followingRedirects()

Please or to participate in this conversation.