【问题标题】:Shoulda-matcher How to validate uniqueness of enum attribute?shoulda-matcher 如何验证枚举属性的唯一性?
【发布时间】:2016-09-05 07:47:10
【问题描述】:

我使用 rspec-rails 和 shoulda-matcher 来测试我的模型。代码如下:

user_ticket.rb

class UserTicket < ActiveRecord::Base
  belongs_to :user
  belongs_to :ticket

  enum relation_type: %w( creator supporter )

  validates_uniqueness_of :relation_type, scope: [:user_id, :ticket_id]
end

user_ticket_spec.rb

RSpec.describe UserTicket, type: :model do
  subject { FactoryGirl.build(:user_ticket) }

  describe 'Relations' do
    it { should belong_to(:user) }
    it { should belong_to(:ticket) }
  end

  describe 'Validations' do
    it { should define_enum_for(:relation_type).with(%w( creator supporter )) }
    # PROBLEM HERE
    it { should validate_uniqueness_of(:relation_type).case_insensitive.scoped_to([:user_id, :ticket_id]) }
  end
end

当我运行测试用例时,结果总是:

Failure/Error: it { should validate_uniqueness_of(:relation_type).case_insensitive.scoped_to([:user_id, :ticket_id]) }

     ArgumentError:
       'CREATOR' is not a valid relation_type

我只是认为应该匹配器想要使用某些relation_type 值来验证唯一性:大写、小写等。我的问题是在这种情况下,如何通过定义的模型验证使测试通过?

【问题讨论】:

    标签: ruby-on-rails rspec shoulda


    【解决方案1】:

    它失败了,因为您要求它不区分大小写地测试 validation。通常,这将用于测试具有不同情况的一系列值导致验证失败。但是,由于枚举,您甚至不允许设置值;它甚至没有进入验证检查。

    它正在使用“creator”和“CREATOR”(至少)测试验证。 enums 区分大小写,因此这将是 enum 中的两个不同值,并且您只声明了“创建者”。当它尝试分配“CREATOR”来测试验证时,您的enum 会感到不安并拒绝允许它。

    您可能希望在不区分大小写的情况下验证唯一性:

    validate_uniqueness_of(:relation_type).ignoring_case_sensitivity
    

    来自validates_uniqueness_of 文档:

    默认情况下,validate_uniqueness_of 将检查验证是否区分大小写:它断言唯一属性的值与预先存在的记录中的相应属性的大小写不同时通过验证。

    使用 ignoring_case_sensitive 跳过此检查。

    或者您可能希望完全跳过测试中的唯一性检查,并相信 rails 只允许 enum 中的唯一值。

    【讨论】:

    • 关于:“跳过唯一性检查”,如果我们需要使用范围怎么办,validates_uniqueness_of :type, scope: :user_id,不幸的是这个检查在这种情况下不起作用:it { is_expected.to validate_uniqueness_of(:type).scoped_to(:user_id) }。所以需要扩展shoulda或者手动写测试
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-22
    • 1970-01-01
    • 1970-01-01
    • 2022-11-15
    • 1970-01-01
    相关资源
    最近更新 更多