Laravel - check what happens after redirect

I have a controller that, after sending email, performs a redirect to the house, for example:

return Redirect::route('home')->with("message", "Ok!"); 

I am writing tests for it, and I'm not sure how to get phpunit to follow the redirect to check for a success message:

 public function testMessageSucceeds() { $crawler = $this->client->request('POST', '/contact', ['email' => ' test@test.com ', 'message' => "lorem ipsum"]); $this->assertResponseStatus(302); $this->assertRedirectedToRoute('home'); $message = $crawler->filter('.success-message'); // Here it fails $this->assertCount(1, $message); } 

If I replaced the code on the controller for this, and I delete the first 2 statements, it works

 Session::flash('message', 'Ok!'); return $this->makeView('staticPages.home'); 

But I would like to use Redirect::route . Is there a way to get PHPUnit to follow the redirect?

+5
source share
2 answers

You can say that the crawler monitors the redirect as follows:

 $crawler = $this->client->followRedirect(); 

so in your case it will be something like:

 public function testMessageSucceeds() { $this->client->request('POST', '/contact', ['email' => ' test@test.com ', 'message' => "lorem ipsum"]); $this->assertResponseStatus(302); $this->assertRedirectedToRoute('home'); $crawler = $this->client->followRedirect(); $message = $crawler->filter('.success-message'); $this->assertCount(1, $message); } 
+6
source

You can force PHPUnit to follow redirects with:

Laravel> = 5.5.19 :

 $this->followingRedirects(); 

Laravel <5.4.12

 $this->followRedirects(); 

Application:

 $response = $this->followingRedirects() ->post('/login', ['email' => ' john@example.com ']) ->assertStatus(200); 

Note. This must be explicitly specified for each request .


For versions between the two :

See https://github.com/laravel/framework/issues/18016#issuecomment-322401713 for a workaround.

+9
source

Source: https://habr.com/ru/post/1208305/


All Articles