【发布时间】:2021-09-06 07:45:50
【问题描述】:
我有一个来自Laravel Documentation 的验证规则,它检查给定 ID 是否属于(Auth)用户,但是测试失败,因为当我转储会话时,我可以看到验证失败,我获取我设置的自定义消息。
我已经在测试中倾倒和死亡工厂,给定的工厂确实属于用户,所以它应该验证,但它不是。
控制器存储方法
$ensureAuthOwnsAuthorId = Rule::exists('authors')->where(function ($query) {
return $query->where('user_id', Auth::id());
});
$request->validate([
'author_id' => ['required', $ensureAuthOwnsAuthorId],
],
[
'author_id.exists' => trans('The author you have selected does not belong to you.'),
]);
PHP单元测试
/**
* @test
*/
function adding_a_valid_poem()
{
// $this->withoutExceptionHandling();
$user = User::factory()->create();
$response = $this->actingAs($user)->post(route('poems.store'), [
'title' => 'Title',
'author_id' => Author::factory()->create(['name' => 'Author', 'user_id' => $user->id])->id,
'poem' => 'Content',
'published_at' => null,
]);
tap(Poem::first(), function ($poem) use ($response, $user)
{
$response->assertStatus(302);
$response->assertRedirect(route('poems.show', $poem));
$this->assertTrue($poem->user->is($user));
$poem->publish();
$this->assertTrue($poem->isPublished());
$this->assertEquals('Title', $poem->title);
$this->assertEquals('Author', $poem->author->name);
$this->assertEquals('Content', $poem->poem);
});
}
任何帮助都将不胜感激,我对此感到摸不着头脑。我唯一的猜测是规则本身在某种程度上是错误的。所有值都添加到数据库中,因此模型很好。
非常感谢!
【问题讨论】:
标签: php laravel validation phpunit validationrules