I'm using Shoulda and Rspec for testing.
When I try this in my test spec it keeps passing when I haven't done the validations in the model:
it { should ensure_inclusion_of(:private).in_array(%w[true false]) }
The attribute is a boolean that is either true or false:
validates_inclusion_of :private, :in => [true, false]
How would I write this correctly?
True
and False
are not strings so don't use %w.
it { should ensure_inclusion_of(:private).in_array([true, false]) }
Update - 10th Apr 2014
This validation will not work in current versions of Shoulda and, as per this recent commit, it will not be fixed but will instead raise an exception.
As any value assigned to a boolean field will be cast to either true (set by true, 1, '1', 't', 'T', 'true', 'TRUE'
) or false (set by anything else) my preferred approach for testing a boolean field is as follows:
For a boolean that allows nulls in the database - no test is required, any possible value will be valid
For a boolean that does not allow nulls in the database - use it { should_not allow_value(nil).for(:field)
which will pass when the validates :field, inclusion: { in: [true,false] }
is set on the model