Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test validation errors throw exact error and message in laravel unit tests

How to test specific validation errors in php unit thrown in validation error ? with below code we could check session has errors, but not the exact error

$this->assertSessionHasErrors();
like image 871
User123456 Avatar asked Mar 27 '17 08:03

User123456


People also ask

How do I show error messages in Laravel?

How do I show laravel validation errors in blade? You can call any() method on $errors variable to check that there are any validation errors exist in it or not. It returns 1 if any errors exist in $errors variable. After that you can call foreach method on $errors->all() and display message using $error variable.

What is assertStatus in Laravel?

} The get method makes a GET request into the application, while the assertStatus method asserts that the returned response should have the given HTTP status code. In addition to this simple assertion, Laravel also contains a variety of assertions for inspecting the response headers, content, JSON structure, and more.

What is the method used to configure validation rules in form request?

Laravel Form Request class comes with two default methods auth() and rules() . You can perform any authorization logic in auth() method whether the current user is allowed to request or not. And in rules() method you can write all your validation rule.


2 Answers

assertSessionHasErrors can receive an array, as documented:

$this->assertSessionHasErrors([
    'field' => 'Field error message.'
]);
like image 116
Gabriel Caruso Avatar answered Oct 12 '22 23:10

Gabriel Caruso


First I use

$this->post() 

instead of

$this->jsonPost()

Dont know why, for certain reason, the session would not come out.

Then I just use

$response->assertSessionHasErrors('field_name', 'Error Message!');

To find out what are the error message, you must dump it

$response->dumpSession();
like image 35
Apit John Ismail Avatar answered Oct 13 '22 01:10

Apit John Ismail