Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way for testing validation errors

I'm testing a form where user must introduce some text between let's say 100 and 500 characters.

I use to emulate the user input:

$this->actingAs($user)
->visit('myweb/create')
->type($this->faker->text(1000),'description')
->press('Save')
->see('greater than');

Here I'm looking for the greater than piece of text in the response... It depends on the translation specified for that validation error.

How could do the same test without having to depend on the text of the validation error and do it depending only on the error itself?

Controller:

public function store(Request $request)
{
    $success = doStuff($request);
    if ($success){
        Flash::success('Created');
    } else {
        Flash::error('Fail');
    }

    return Redirect::back():
}

dd(Session::all()):

 `array:3 [
  "_token" => "ONoTlU2w7Ii2Npbr27dH5WSXolw6qpQncavQn72e"
  "_sf2_meta" => array:3 [
    "u" => 1453141086
    "c" => 1453141086
    "l" => "0"
  ]
  "flash" => array:2 [
    "old" => []
    "new" => []
  ]
]
like image 725
javier_domenech Avatar asked Jan 13 '16 12:01

javier_domenech


2 Answers

get the MessageBag object from from session erros and get all the validation error names using $errors->get('name')

    $errors = session('errors');
    $this->assertSessionHasErrors();
    $this->assertEquals($errors->get('name')[0],"The title field is required.");

This works for Laravel 5 +

like image 166
User123456 Avatar answered Oct 04 '22 05:10

User123456


you can do it like so -

$this->assertSessionHas('flash_notification.level', 'danger'); if you are looking for a particular error or success key.

or use $this->assertSessionHasErrors();

like image 41
Ayo Akinyemi Avatar answered Oct 04 '22 03:10

Ayo Akinyemi