ShawnDL's avatar

Access Validation Errors in Test

Is there a way to access validation errors in phpunit tests. I am testing if our validation logic is working, but I always have to hard code what the error message is. However, every time there is a simple change in our validation logic then I have to update my test. For example, if I change the minimum number of categories to 3. Is there a way I can find out what the validation error message so I don't always have to hard code it. By the way, it is also a restful api so I can't access the session

        $this->json('post', 'sampleurl.com', $post)
            ->assertJsonFragment([
                'categories' => ['Please provide at least 2 categories.'] . // $request->getErrorMessage('categories')
            ]);
0 likes
1 reply
bobbybouwmann's avatar
Level 88

There are translation files available. So for example when you have a required field you could be doing something like this

$this->json('post', 'sampleurl.com', $post)
    ->assertJsonFragment([
        'categories' => trans('validation.required', ['attribute' => 'categories']), 
    ]);

You only need to determine what fields you need to replace (in this case :attribute) and then you should get the real validation message ;)

Please or to participate in this conversation.