Laravel 存在无法使用 phpunit 验证用户 ID 的自定义验证规则

Laravel exists custom validation rule unable to validate user id with phpunit

我有一个取自 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);
    });
}

如有任何帮助,我将不胜感激,我正在为此摸不着头脑。我唯一的猜测是规则本身在某种程度上是错误的。所有值都添加到数据库中,因此模型很好。

非常感谢!

在你的Rule::exists()中,你需要指定列,否则laravel将字段名作为列名

Rule::exists('authors', 'id')

由于未指定列,您的代码基本上是在做

Rule::exists('authors', 'author_id')