phpunit test returns 302 for bad validation, why not 422

安稳与你 提交于 2019-11-29 17:09:42

问题


I have a request class that fails for a post request. When I call it with ajax I get an 422 because the validation rules failed. But when I use phpunit for test for the same route with same values, it returns a 302.

I also get no error messages like "field foobar is required" just the 302.

So how can I get the error messages to check if they are equals or not?

Here is my testcode:

//post exam
$this->post('modul/foo/exam', [
    'date' => '2016-01-01'
])
    ->assertResponseStatus(200);

//post exam again
$this->post('modul/foo/exam', [
    'date' => '2016-01-01'
])
    ->assertResponseStatus(302); //need to get 422 with th errors because its an api

回答1:


When the validation on the FormRequest fails, it checks to see if the request was ajax or if it accepts a json response. If so, it will return a json response with the 422 status code. If not, it will return a redirect to a specified url (previous, by default). So, in order to get the response on failure you're looking for (422), you need to make a json request or an ajax request.

JSON

To make a json request, you should use the json() method:

//post exam
$this->json('POST', 'modul/foo/exam', [
        'date' => '2016-01-01'
    ])
    ->assertResponseStatus(200);

//post exam again
$this->json('POST', 'modul/foo/exam', [
        'date' => 'some invalid date'
    ])
    ->assertResponseStatus(422);

AJAX

To make an ajax request, you need to add in the ajax headers. For this, you can continue to use the post() method:

//post exam
$this->post(, 'modul/foo/exam', [
        'date' => '2016-01-01'
    ], ['HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest'])
    ->assertResponseStatus(200);

//post exam again
$this->post('modul/foo/exam', [
        'date' => 'some invalid date'
    ], ['HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest'])
    ->assertResponseStatus(422);


来源:https://stackoverflow.com/questions/35025347/phpunit-test-returns-302-for-bad-validation-why-not-422

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!