Laravel 5.8 Illuminate\Validation\ValidationException: The given data was invalid

2.2k views Asked by At

I have store method in my controller like this

public function store()
{
     request()->validate(['family'=>'required']);
     User::create(request()->all());
     return redirect('/users');
}

and test method like this

/** @test */
public function a_user_require_family()
{
    $this->withoutExceptionHandling();
    $this->post('/users', [])->assertSessionHasErrors('family');
}

It show me this:

1) Tests\Feature\UserTest::a_user_require_family
Illuminate\Validation\ValidationException: The given data was invalid.

2

There are 2 answers

0
Sapnesh Naik On BEST ANSWER

You are using assertSessionHasErrors('family') which catches a ValidationException on the key family only if the key was passed in the request body and then failed your validation.

But in your case you are not passing the said key at all (You send an empty body []).

You need to use assertSessionMissing() in this case.

Try:

$this->post('/users', [])->assertSessionMissing('family');

Laravel Documentation : https://laravel.com/docs/5.8/http-tests#assert-session-missing

1
Azeame On

You cannot use $this->withoutExceptionHandling() and also ->assertSessionHasErrors('family') because all Validation errors are Exceptions which get handled by Illuminate\Validation\ValidationException which you are expressly forbidding to run.

Simply remove $this->withoutExceptionHandling() and your test should pass.