客户表中有字段名称处于活动状态。它在customer.rb中验证如下:
validates :active, :presence => true
以下是测试字段short_name的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
对short_name的验证是:
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)>'
似乎分配给字段active的false值被rspec视为空白或nil,并且数据验证检查失败。试图使用0表示false,它会导致相同的错误。如果删除字段active的验证,则会传递rspec案例。
答案 0 :(得分:6)
这不是一个rspec问题,它与Rails的验证有关。我想你的active
字段是一个布尔值,引用validates_presence_of
文档:
如果要验证是否存在布尔字段(实际值为true和false),则需要使用validates_inclusion_of:field_name,:in =&gt; [true,false]这是由于Object#blank的方式?处理布尔值。 false.blank? #=&gt;真
因此,只需将验证器更改为以下内容(假设您需要“性感”语法),它应该可以正常工作:
validates :active, :inclusion => [true, false]