Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/57.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails matcher应该如何验证枚举属性的唯一性?_Ruby On Rails_Rspec_Shoulda - Fatal编程技术网

Ruby on rails matcher应该如何验证枚举属性的唯一性?

Ruby on rails matcher应该如何验证枚举属性的唯一性?,ruby-on-rails,rspec,shoulda,Ruby On Rails,Rspec,Shoulda,我使用rspec rails和shoulda matcher来测试我的模型。代码如下: user\u 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,

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

user\u 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
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

我只是觉得matcher应该用一些类型的
关系类型
值来验证唯一性:大写、小写等等。我的问题是,在这种情况下,如何使用这样的定义模型验证使测试通过?

它失败了,因为您要求它不敏感地测试验证用例。通常,这将用于测试一系列值,不同的情况会导致验证失败。但是,由于枚举的原因,甚至不允许您设置该值;它甚至没有进入验证检查

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

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

validate_uniqueness_of(:relation_type).ignoring_case_sensitivity
从文档中:

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

使用忽略大小写敏感度跳过此检查

或者您可能希望完全跳过测试中的唯一性检查,并相信rails只允许
枚举中的唯一值关于:“跳过唯一性检查”,如果我们需要使用范围,
验证:type,scope::user_id的唯一性,不幸的是,这种检查在这种情况下不起作用:
it{is_应为。验证(:type)的唯一性。作用域为(:user_id)}
。因此需要扩展
shoulda
或编写测试手册lyseems legit