I'm trying to ensure that a field of my model is a boolean, but my tests keep on failing.
After reading this: Validating boolean value in Rspec and Rails and this Rails: how do I validate that something is a boolean? I ended up doing it like so:
class Model < ActiveRecord::Base
validates :my_field, :inclusion => { :in => [true, false] }
end
I've tried testing this a few different ways (using rspec and shoulda matchers) and since my tests keep on failing, I'm right now down to the dumbest possible (?) way. Still, the tests don't pass and I'm guessing that there's some mechanism that converts the value somewhere.
Here's what I'm using to find out what's going on:
# create instance without setting value ...
# these work as expected
model_instance.valid?.should be_false # passes
model_instance.my_field = true
model_instance.valid?.should be_true # passes
model_instance.my_field = false
model_instance.valid?.should be_true # passes
# works as expected
model_instance.my_field = ""
model_instance.valid?.should be_false # passes
# these should pass but fail
model_instance.my_field = "foo"
model_instance.my_field.should == "foo" # fails as well, my_field == false
model_instance.valid?.should be_false # fails
model_instance.my_field = "false"
model_instance.my_field.should == "false" # fails as well, my_field == false
model_instance.valid?.should be_false # fails
model_instance.my_field = "123"
model_instance.valid?.should be_false # fails
model_instance.my_field = "true"
model_instance.my_field.should == "true" # fails as well, my_field == true
model_instance.valid?.should be_false # fails
What am I missing? Seems the value is converted in a somewhat logical fashion but where and how to prevent it? How to do this kind of validation properly?