2011-12-08 4 views
2

カスタマーテーブルにフィールド名が有効です。これはcustomer.rbに以下のように検証:rspecではfalseがnilとみなされますか?

validates :active, :presence => true 

ここフィールドSHORT_NAMEテストする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 

検証は、次のとおり

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とみなされ、データ検証チェックに失敗したようです。 falseに0を使用しようとしましたが、同じエラーが発生します。 field activeの検証を削除すると、rspecケースは成功します。

答えて

4

これはrspecの問題ではなく、Railsの検証に関連しています。

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

だから、単純に(あなたは「セクシー」構文をしたいと仮定して)次のようにあなたのバリデータを変更し、それが動作するはずです::私はあなたのactiveフィールドがvalidates_presence_of文書を引用して、ブール値とであると仮定し

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

あなたは正しいです。ありがとう。 – user938363

関連する問題