FactoryGirl: assigning false to boolean

In my Factory, I have a boolean field (evaluated) that I am trying to set to false. I want the field to be required and always set to either true or false

Model

validates_presence_of :evaluated 

Factory

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

In the test

  it { should validate_presence_of(:evaluated) } 

When i started it

  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 

If I change the value to true, the test passes

  evaluated true 

How to set up Factory with false values ​​for Booleans?

+6
source share
1 answer

I would prefer to use the inclusion_of check instead of the presence check.

From rails doc ,

If you want to check for the presence of a logical field (where the actual values ​​are true and false), you will want to use

validates_inclusion_of :field_name, in: [true, false]

This is due to how Object#blank? processes boolean values

ie false.blank? # => true false.blank? # => true

Then your test will be something like this

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

+12
source

All Articles