2011-12-08 68 views
2

客戶表中有活動的字段名稱。它如下文驗證在customer.rb:在rspec中被認爲是否爲false?

validates :active, :presence => true 

這裏是RSpec的代碼來測試一個字段SHORT_NAME:

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)>' 

似乎分配給字段活動的錯誤值在rspec中被認爲是空白或零,並且數據驗證檢查失敗。試圖使用0作爲錯誤,它會導致相同的錯誤。如果刪除對活動字段的驗證,rspec情況會通過。

回答

4

這不是一個rspec問題,它與Rails的驗證有關。我想你active字段是一個布爾值,並引述validates_presence_of文檔:

If you want to validate the presence of a boolean field (where the real values are true and false), you will want to use validates_inclusion_of :field_name, :in => [true, false] This is due to the way Object#blank? handles boolean values. false.blank? # => true

所以只需將您的驗證更改爲類似如下(假設你想要的「性感」語法),它應該工作:

validates :active, :inclusion => [true, false] 
+0

你說得對。謝謝。 – user938363

相關問題