Summer Sale! All accounts are 50% off this week.

Rretzko's avatar
Level 15

Testing for validation failures

Hi - I'm testing to ensure my validations are working as expected. The controller uses a FormRequest for validation. The test function is:

public function test_user_profile_validation_fails_when_first_is_missing()
    {
        $this->withoutExceptionHandling();

        $user = User::factory()->create();
        auth()->loginUsingId($user->id);

        $response = $this->post('profile/update/'.$user->id,
            [
                'first' => '',
                'last' => 'Hunt',
            ]);

        $response->assertStatus(302)
                 ->assertValidationErrors(['first']);
    }

and this is controller's update function:

public function update(ProfileRequest $request, User $user)
    {
        return route('profile',['user' => auth()->user()]);
    }

and the ProfileRequest

public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, mixed>
     */
    public function rules()
    {
        return [
            'first' => ['string','required'],
            'last' => ['string','required'],
        ];
    }

I expect this test to pass, but I get an error AND the test fails:

 Illuminate\Validation\ValidationException : The first must be a string. (and 1 more error)

which is true but frustrates my ability to test the condition. I'm sure I've got something wrong and would appreciate your guidance! Thanks.

0 likes
2 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

Remove

$this->withoutExceptionHandling()

Also you are missing redirect

return redirect()->route('profile',['user' => auth()->user()]); 
Rretzko's avatar
Level 15

Thanks @sinnbeck ! I made those edits and ran into:

BadMethodCallException : Call to undefined method Illuminate\Http\RedirectResponse::assertValidationErrors()

I'm not sure where I got this from as it is not in the phpunit docs, so I removed that command, and the test ran green. Now, however, the test ran green if the 'first' field had a value or if it was empty. It took me a bit a head-scratching to realize that both success and failure resulted in a redirect. Changing the Controller to a return view() solved that problem. I appreciate your help and quick turn-around!

Please or to participate in this conversation.