【问题标题】:How to write a test for validates_uniqueness_of with scope and presence: true RSpec Rails如何使用范围和存在为 validates_uniqueness_of 编写测试:真正的 RSpec Rails
【发布时间】:2020-05-24 08:51:38
【问题描述】:

尝试编写一个测试来验证 :user_id 与范围 :board_id 的唯一性。

型号:

class Membership < ApplicationRecord
  belongs_to :board
  belongs_to :user
  validates_uniqueness_of :user_id, scope: :board_id, presence: true
end

我尝试像这样测试它:

it { should validate_uniqueness_of(:user_id) } 
it expect.to have_many(:membership).through(:board_id)

感谢您的帮助。

【问题讨论】:

    标签: ruby-on-rails testing rspec scope rspec-rails


    【解决方案1】:

    如果使用 shoulda-matchers 它可以在两个期望中完成(即使它是单个模型线):

    it { should validate_presence_of(:user_id) }
    it { should validate_uniqueness_of(:user_id).scoped_to(:board_id) }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-17
    • 2017-07-06
    • 1970-01-01
    相关资源
    最近更新 更多