Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rspec validation failed - attribute can't be blank but it isn't blank

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?

like image 385
Matthew Berman Avatar asked Oct 15 '11 22:10

Matthew Berman


1 Answers

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.

like image 161
bricker Avatar answered Nov 10 '22 02:11

bricker