【问题标题】:Laravel exists custom validation rule unable to validate user id with phpunitLaravel 存在无法使用 phpunit 验证用户 ID 的自定义验证规则
【发布时间】: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


    【解决方案1】:

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

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

    由于没有指定列,你的代码基本上是在做

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

    【讨论】:

    • 我不敢相信它这么简单!感谢您的帮助。 :)
    猜你喜欢
    • 2014-04-22
    • 2017-12-01
    • 2017-04-11
    • 2018-02-18
    • 2014-11-25
    • 2018-10-25
    • 2019-02-12
    • 2016-11-22
    • 2018-06-03
    相关资源
    最近更新 更多