In Laravel 4, when you perform a validation on a form submission, you can pass the errors from the Validator back to the view
return Redirect::back()
->withErrors($this->validator)
->withInput();
So that the errors can be shown on the view
{{-- Error box --}}
@if ($errors->count())
<div class='error-box'>
<ul>
@foreach ($errors->all() as $error)
<li>{{{ $error }}}</li>
@endforeach
</ul>
</div>
@endif
The $errors variable is the a Illuminate\Support\ViewErrorBag object, which apparently is a Laravel-thing used to handle errors.
This works in practice great, so fine by me.
Now let's talk testing:
This is my test for a Contact Form, when the email is invalid:
public function testFailureInvalidEmail() {
$data = ['email' => 'invalid', 'message' => "lorem ipsum"];
// Make request
$this->post('/contact', $data, [], ['HTTP_REFERER' => URL::route('contact.create')]);
// Check redirects
$this->assertResponseStatus(302);
//Check redirects to the right place
$this->assertRedirectedToRoute('contact.create');
// Check old input is forwarded
$this->assertHasOldInput();
// Check there are errors
$this->assertSessionHasErrors();
// Check the email is the error failing
$this->assertSessionHasErrors('email');
// Follow redirect
$this->client->followRedirect();
// Check HTTP Code 200
$this->assertResponseOk();
// Check old input is present
$this->assertElementMatches('input[name=email]', 1, ['value' => $data['email']]);
$this->assertElementMatches('textarea[name=message]', 1, [], [], $data['message']);
}
Everything works out great:
- I set the REFERER on the call, to handle the
Redirect::back - I check the redirect
- the old input
- the errors in the session
- The form elements are re-filled with the old input (The function
assertElementMatchesis just a method I defined to simplify the task)
MY PROBLEM:
There is one thing that I do not know how to test. That is that the messages are actually rendering on the DOM. For some reason if I add this check:
$this->assertCount(1, $this->filter(".error-box"));
I get an failure, saying that "0 does not match 1".
What can I do to test the rendering of the error?
Aucun commentaire:
Enregistrer un commentaire