0

I have this validation in my model violin.rb:

  validates :bow_included, presence: true
  validates_inclusion_of :bow_included, in: [true, false]

And in my spec file violin_spec.rb I have the following (I use shoulda_matchers gem):

it { should validate_presence_of :bow_included }
it { should validate_inclusion_of(:bow_included).in_array([true, false]) }

When I run the test, I get this:

1) Violin validations should ensure inclusion of bow_included in [true, false]

 Failure/Error: it { should validate_inclusion_of(:bow_included).in_array([true, false]) }
   [true, false] doesn't match array in validation
 # ./spec/models/violin_spec.rb:17:in `block (3 levels) in <top (required)>'

However, I have the same validation and test in another model and there it works fine.

Could you please help me find out what's going on here?

Denis Yakovenko
  • 3,241
  • 6
  • 48
  • 82

1 Answers1

1

If you take a look at their documentation, they say that they don't recommend this and that it will produce warnings: https://github.com/thoughtbot/shoulda-matchers/blob/master/lib/shoulda/matchers/active_model/validate_inclusion_of_matcher.rb#L52

The tl;dr is:

There is never a case where a boolean column will be anything but true, false, or nil, as ActiveRecord will type-cast an incoming value to one of these three values. That means there isn't any way we can refute this logic in a test.

I know that doesn't answer your question directly, but if you're using boolean values in your AR models, then those tests aren't necessary anyway.

Ian Selby
  • 3,241
  • 1
  • 25
  • 18
  • Well, I thought I needed tests because for boolean columns the test like this: `it { should allow_value("whatever").for(:bow_included) }` passes without any problems. – Denis Yakovenko Aug 11 '15 at 16:01
  • That just gets type-cast to true, if memory serves. – Ian Selby Aug 11 '15 at 16:13
  • This is more thoroughly answered here: http://stackoverflow.com/questions/5170008/rails-validating-inclusion-of-a-boolean-fails-tests – Ian Selby Aug 11 '15 at 17:38