如何在 Rails Rspec 中使用 Scope 编写测试用例以实现唯一性

问题描述 投票:0回答:1

我想为此验证编写 RSpec 测试,但它总是给我错误

validates :post_id, uniqueness: { scope: :user_id }

我正在使用这个解决方案,但它不起作用

it { is_expected.to validate_uniqueness_of(:post_id).scoped_to(:user_id, :created_at) }

错误

Like is expected to validate that :post_id is case-sensitively unique within the scope of :user_id and :created_at
  Failure/Error: it { is_expected.to validate_uniqueness_of(:post_id).scoped_to(:user_id, :created_at) }

    Expected Like to validate that :post_id is case-sensitively unique
    within the scope of :user_id and :created_at, but this could not be
    proved.
      Expected the validation to be scoped to :user_id and :created_at, but
      it was scoped to :user_id instead.

任何帮助

ruby-on-rails ruby rspec rspec-rails
1个回答
1
投票

如果模型中有

validates :post_id, uniqueness: { scope: :user_id }

那么你需要规格

it { is_expected.to validate_uniqueness_of(:post_id).scoped_to(:user_id) }

it { should validate_uniqueness_of(:post_id).scoped_to(:user_id) }
© www.soinside.com 2019 - 2024. All rights reserved.