Ruby on rails rspec中false是否被视为零?
客户表中有活动的字段名。它在customer.rb中验证如下:Ruby on rails rspec中false是否被视为零?,ruby-on-rails,rspec,Ruby On Rails,Rspec,客户表中有活动的字段名。它在customer.rb中验证如下: validates :active, :presence => true 以下是测试字段短名称的rspec代码: it "should be OK with duplicate short_name in different active status" do customer = Factory(:customer, :active => false, :short_name => "test user")
validates :active, :presence => true
以下是测试字段短名称的rspec代码:
it "should be OK with duplicate short_name in different active status" do
customer = Factory(:customer, :active => false, :short_name => "test user")
customer1 = Factory.build(:customer, :active => true, :short_name => "Test user")
customer1.should be_valid
end
短_名称的验证为:
validates :short_name, :presence => true, :uniqueness => { :scope => :active }
上述代码导致错误:
1) Customer data integrity should be OK with duplicate short_name in different active status
Failure/Error: customer = Factory(:customer, :active => false, :short_name => "test user")
ActiveRecord::RecordInvalid:
Validation failed: Active can't be blank
# ./spec/models/customer_spec.rb:62:in `block (3 levels) in <top (required)>'
1)客户数据完整性应正常,在不同的活动状态下使用重复的短名称
失败/错误:customer=Factory(:customer,:active=>false,:short\u name=>“测试用户”)
ActiveRecord::RecordInvalid:
验证失败:活动不能为空
#./spec/models/customer_spec.rb:62:in'block(3层)in'
rspec似乎认为分配给字段active的假值为空或为零,并且未通过数据验证检查。尝试将0用作false,但它会导致相同的错误。如果删除活动字段的验证,则rspec案例通过。这不是rspec问题,它与Rails的验证有关。我假设您的
active
字段是一个布尔值,引用验证文档的存在:
如果要验证布尔字段的存在性(其中实值为true和false),则需要使用validates_inclusion_of:field_name,:in=>[true,false]这是由于Object#blank?处理布尔值。false.blank?#=>真的
因此,只需将验证器更改为以下内容(假设您需要“sexy”语法),它就可以工作了:
validates :active, :inclusion => [true, false]
以下是文档链接: