【发布时间】:2021-06-05 02:18:02
【问题描述】:
我正在通过请求传递一个 json 对象数组以在控制器中进行验证:
控制器
public function store(Request $request)
{
$this->validate($request, [
'situation' => 'required',
]);
$emotions= ['data' => $request->input('emotions')];
$emotionsValidation = \Illuminate\Support\Facades\Validator::make($emotions, [
'data.*.id' => 'integer|between:1,70',
'data.*.intensity' => 'integer|between:0,100',
'data.*.new_intensity' => 'integer|between:0,100'
]);
if($emotionsValidation->fails()) {
return response(['error' => 'There was a problem with the emotions you submitted.'],422);
}
$emotions= ['data' => $request->input('emotions')];
$emotionsValidation = \Illuminate\Support\Facades\Validator::make($emotions, [
'data.*.id' => 'integer|between:1,70',
'data.*.intensity' => 'integer|between:0,100',
'data.*.new_intensity' => 'integer|between:0,100'
]);
if($emotionsValidation->fails()) {
return response(['error' => 'There was a problem with the emotions you submitted.'],422);
}
//Return record resource
}
验证工作正常,但测试并没有像应有的那样通过:
测试
/** @test */
public function a_records_json_emotions_must_be_integers()
{
$this->actingAs($creator = factory('App\User')->create());
$thought = [
'user_id' => 1,
'situation' => 'A situation',
'emotions' => json_decode("[{'id': 2000, 'intensity': 100, 'new_intensity': 20}]")
];
//dd(json_encode("[{'id': 2000, 'intensity': 100, 'new_intensity': 20}]"));
$response = $this->json('POST', '/api/thought/record', $thought )
->assertStatus(422);
}
当我取消注释 dd(json_encode("[{'id': 2000, 'intensity': 100, 'new_intensity': 20}]")); 时,我得到:""[{'id': 2000, 'intensity': 100, 'new_intensity': 20}]""
测试信息
- Tests\Feature\UserThoughtRecordsTest::a_thought_records_json_emotions_must_be_integers 预期状态码 422,但收到 201。 无法断言 422 与 201 相同。
如何让这个测试通过?
【问题讨论】:
标签: laravel validation phpunit