Shoulda-matchers: ensure_inclusion_of doesn't work well when type is a boolean

Created on 26 Apr 2014  路  6Comments  路  Source: thoughtbot/shoulda-matchers

rails rescue app with silly booleans

#schema 
t.boolean  "recommended"

#model 
validates_inclusion_of :recommended, :in => [true, false, 0, 1, '0', '1'], :allow_blank => true

#spec
it { should ensure_inclusion_of(:recommended).in_array([true, false, 0, 1, '0', '1']) }

#failure
#doesn't match array in validation

Most helpful comment

I solved problem with like this code.

it { should allow_value(%w(true false)).for(:done) }

All 6 comments

Is that the full error message you're getting or is there anything more to that?

This is the full error message I get

Failure/Error: it { should ensure_inclusion_of(:active).in_array([true, false]) }
  [true, false] doesn't match array in validation

code

validates :active, inclusion: { in: [true, false] }

spec

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

Sorry for the late reply on this. Are you still getting this error?

Running this test using version 2.6.2 of shoulda-matchers results in the following message.

Warning from shoulda-matchers:

You are using `ensure_inclusion_of` to assert that a boolean column allows
boolean values and disallows non-boolean ones. Assuming you are using
`validates_format_of` in your model, be aware that it is not possible to fully
test this, and in fact the validation is superfluous, as boolean columns will
automatically convert non-boolean values to boolean ones. Hence, you should
consider removing this test and the corresponding validation.

Which I think is silly considering this exact validation is recommended in the Rails Guide. http://guides.rubyonrails.org/active_record_validations.html#presence

Since false.blank? is true, if you want to validate the presence of a boolean field you should use validates :field_name, inclusion: { in: [true, false] }.

Alright, thanks for the feedback. I agree the message is opinionated and I'll take that part out.

Can I close this, then?

I solved problem with like this code.

it { should allow_value(%w(true false)).for(:done) }

Was this page helpful?
0 / 5 - 0 ratings