如何在单元测试中将模型绑定到请求
How to bind a model to a request in unit tests
我正在努力将模型绑定到单元测试中的请求,以便可以在表单请求中检索模型的关系。
这是表单请求:
class TimeSlotUpdateRequest extends FormRequest
{
public function rules(): array
{
return [
'time' => [
'required', 'string', 'max:50',
Rule::unique('time_slots')
->where('schedule_id', $this->timeSlot->schedule->id)
->ignore($this->timeSlot),
],
];
}
}
这是测试(assertExactValidationRules
来自 Jason McCreary 的 Laravel 测试断言包):
/** @test **/
public function it_verifies_the_validation_rules(): void
{
$timeSlot = TimeSlot::factory()->create();
$request = TimeSlotUpdateRequest::create(
route('admin.timeSlots.update', $timeSlot),
'PATCH'
)
->setContainer($this->app);
$request->setRouteResolver(function () use ($request) {
return Route::getRoutes()->match($request);
});
$this->assertExactValidationRules([
'time' => [
'required', 'string', 'max:50',
Rule::unique('time_slots')
->where('schedule_id', $timeSlot->schedule->id)
->ignore($timeSlot->id),
],
], $request->rules());
}
当从测试和表单请求中删除 where 子句时测试通过,但 where 子句失败并出现错误 ErrorException: Trying to get property 'schedule' of non-object
我尝试使用 xDebug 单步执行请求,但仍然不明白如何完成路由模型绑定。
如何将 $timeSlot
模型绑定请求或路由,以便在表单请求中访问 schedule
关系?
我们将不胜感激。
路由模型绑定是通过中间件 SubstituteBindings
中间件处理的。所以请求必须通过中间件堆栈。由于您没有这样做,我想您可以自己在路线上设置参数:
$route->setParameter($name, $value);
$route
将是 return 从 match
编辑的路由对象。
此外,在处理请求时,如果你想要一个路由参数,你应该明确说明它并且不要使用动态 属性 因为它会 return 在它回退到 return输入一个路由参数:
$this->route('timeSlot');
我正在努力将模型绑定到单元测试中的请求,以便可以在表单请求中检索模型的关系。
这是表单请求:
class TimeSlotUpdateRequest extends FormRequest
{
public function rules(): array
{
return [
'time' => [
'required', 'string', 'max:50',
Rule::unique('time_slots')
->where('schedule_id', $this->timeSlot->schedule->id)
->ignore($this->timeSlot),
],
];
}
}
这是测试(assertExactValidationRules
来自 Jason McCreary 的 Laravel 测试断言包):
/** @test **/
public function it_verifies_the_validation_rules(): void
{
$timeSlot = TimeSlot::factory()->create();
$request = TimeSlotUpdateRequest::create(
route('admin.timeSlots.update', $timeSlot),
'PATCH'
)
->setContainer($this->app);
$request->setRouteResolver(function () use ($request) {
return Route::getRoutes()->match($request);
});
$this->assertExactValidationRules([
'time' => [
'required', 'string', 'max:50',
Rule::unique('time_slots')
->where('schedule_id', $timeSlot->schedule->id)
->ignore($timeSlot->id),
],
], $request->rules());
}
当从测试和表单请求中删除 where 子句时测试通过,但 where 子句失败并出现错误 ErrorException: Trying to get property 'schedule' of non-object
我尝试使用 xDebug 单步执行请求,但仍然不明白如何完成路由模型绑定。
如何将 $timeSlot
模型绑定请求或路由,以便在表单请求中访问 schedule
关系?
我们将不胜感激。
路由模型绑定是通过中间件 SubstituteBindings
中间件处理的。所以请求必须通过中间件堆栈。由于您没有这样做,我想您可以自己在路线上设置参数:
$route->setParameter($name, $value);
$route
将是 return 从 match
编辑的路由对象。
此外,在处理请求时,如果你想要一个路由参数,你应该明确说明它并且不要使用动态 属性 因为它会 return 在它回退到 return输入一个路由参数:
$this->route('timeSlot');