With Laravel it makes it really easy to test HTTP requests by using the trait MakesHttpRequests
.
This has all the methods you will need to run HTTP requests from your feature tests.
One thing you will often come across in testing your application is when you need to test redirects. For example when you post to a form you might want to redirect to a different page on success and then redirect back to the previous page if the form errors.
There are a few methods you need to be aware of to be able to tests these:
-
from()
-
assertRedirect()
From is used to define the HTTP referrer page
AssertRedirect will allow you to check what page the app redirects to.
Testing Back()
In your controllers Laravel provides an easy way to redirect back to the previous page. In the example of a contact form you may have a GET
route to display the form then a POST
route to send the email.
Route::get('contact', 'ContactController@index');
Route::post('contact/send', 'ContactController@send');
It's common in the send
method to redirect back to GET
route when the contact form fails to send.
In Laravel this can be done by using the response helper.
return response()->back();
To be able to test this you need to use the from()
method on the MakesHttpRequests
, this will tell Laravel where to redirect back to. You will use this on the request object in your test.
$response = $this->from('contact')->post('contact/send', [
'name' => 'John',
'email' => '[email protected]',
'message' => 'This is the email message',
]);
Then you simply use the assertRedirect
method to make sure it redirects to the correct route.
$response->assertRedirect('contact');