I just wrote a test for testing if a new user creation also consists of an admin setting. Here is the test:
describe User do
before(:each) do
@attr = {
:name => "Example User",
:email => "[email protected]",
:admin => "f"
}
end
it "should create a new instance given valid attributes" do
User.create!(@attr)
end
it "should require a name" do
no_name_user = User.new(@attr.merge(:name => ""))
no_name_user.should_not be_valid
end
it "should require an email" do
no_email_user = User.new(@attr.merge(:email => ""))
no_email_user.should_not be_valid
end
it "should require an admin setting" do
no_admin_user = User.new(@attr.merge(:admin => ""))
no_admin_user.should_not be_valid
end
end
Then, in my User model I have:
class User < ActiveRecord::Base
attr_accessible :name, :email, :admin
has_many :ownerships
has_many :projects, :through => :ownerships
email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :name, :presence => true,
:length => { :maximum => 50 }
validates :email, :presence => true,
:format => { :with => email_regex },
:uniqueness => { :case_sensitive => false }
validates :admin, :presence => true
end
I clearly created a new user with an admin setting, so why is it saying it's false? I created the migration for the admin setting as admin:boolean. Did I do something wrong?
Here's the error:
Failures:
1) User should create a new instance given valid attributes
Failure/Error: User.create!(@attr)
ActiveRecord::RecordInvalid:
Validation failed: Admin can't be blank
# ./spec/models/user_spec.rb:14:in `block (2 levels) in <top (required)>'
Oddly enough, when I comment out validates :admin, :presence => true, the test creates the user correctly but fails on "User should require an admin setting"
EDIT: When I change the @attr :admin value to "t" it works! Why doesn't it work when the value is false?
From the rails guides:
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] }.
Basically, it looks like ActiveRecord is converting your "f" to false
before the validation, and then it runs false.blank?
and returns true
(meaning that the field is NOT present), causing the validation to fail. So, to fix it in your case, change your validation:
validates :admin, :inclusion => { :in => [true, false] }
Seems a little hacky to me... hopefully the Rails developers will reconsider this in a future release.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With