2016-03-08 101 views
6

在我的工廠中,我有一個布爾字段(求值),我試圖設置爲false。我想需要的領域,始終設置爲真正FactoryGirl:爲布爾值賦值爲false

型號

validates_presence_of :evaluated 

FactoryGirl.define do 
    factory :submission do 
    evaluated true 
    score 1.5 
    ranking 1.5 
    submission_type "user" 
    . 
    . 
    end 
end 

在測試

it { should validate_presence_of(:evaluated) } 

當我跑步它

 Failure/Error: expect(@submission).to be_valid 
    expected #<Submission id: nil, competition_id: 163, user_id: 134, team_id: nil, evaluated: false, score: 1.5, ranking: 1.5, submission_type_cd: "user", withdrawn: true, withdrawn_date: "2016-02-08", created_at: nil, updated_at: nil> to be valid, but got errors: Evaluated can't be blank 

如果我的值更改爲true,測試通過

evaluated true 

我怎樣才能建立一個工廠與布爾假值?

+2

它更是你無法驗證布爾值的存在。 'false.present? => false' –

+0

那麼最好的選擇是將它添加爲db級別的非空值? – ardochhigh

+0

是的,這就是我要做的 –

回答

12

我寧願使用inclusion_of驗證而不是presence驗證。

從軌doc

如果您想驗證一個布爾字段(其中實際值是true和false)的情況下,你將要使用

validates_inclusion_of :field_name, in: [true, false]

這是由於道路Object#blank?處理布爾值

false.blank? # => true

然後你的測試會是這樣,

it { should ensure_inclusion_of(:field_name).in_array([true, false]) }