I’m pretty confused how to validate boolean values in Rspec and Rails. I understand everything except for false and nil are taken as true in Ruby. But when I use MySQL with Rails, it uses 1 for true and 0 for false (if my understanding is correct).
I have the following model spec. I’d like to test boolean value for superuser attribute.
- How can I write specs here?
- How can I write implementation code here?
-
Are my specs and implementation code specific to a specific database (like MySQL and PostgreSQL)?
require 'spec_helper' describe User do before(:each) do @valid_attributes = { :username => "mike", :password => "super_encryped_password", :email => "mike@example.com", :superuser => true } end it "should create a new instance given valid attributes" do User.create!(@valid_attributes) end it "should have true or false for superuser" do @valid_attributes[:superuser] = "hello" User.new(@valid_attributes).should have(1).error_on(:superuser) end end
One important thing is that ActiveRecord does typecasting behind the scenes, so you do not have to worry about how your database stores boolean values. You even need not validate that a field is boolean, as long as you set that field as boolean when preparing your migration. You may want to make sure the field is not
nilthough, with avalidates_presence_of :superuserdeclaration in your model class.