Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Rspec Model Spec User :email ActiveRecord::RecordInvalid

Trying to figure out why my rspec test is failing. Most notable is the Failure message that seems contradictory. Stating I have an ActiveRecord::RecordInvalid error and that is exactly what I'm asserting should happen.

Here is my user.rb

...
validates_presence_of :email
...

Here is my users_spec.rb

...
it "is invalid without email" do 
  Factory(:user, email: nil).should raise_error(ActiveRecord::RecordInvalid)
end
...

here is the output:

Failures:

  1) User a user (in general) is invalid without email
     Failure/Error: Factory(:user, email: nil).should raise_error(ActiveRecord::RecordInvalid)
     ActiveRecord::RecordInvalid:
       Validation failed: Email is invalid, Email can't be blank
     # ./spec/models/user_spec.rb:34:in `block (3 levels) in <top (required)>'

Originally I was testing it this way but it kept failing, so I decided to specify on what error I was expecting.

it "is invalid without email" do 
  Factory(:user, email: nil).should_not be_valid
end
like image 470
botbot Avatar asked Nov 17 '25 20:11

botbot


1 Answers

The reason your code isn't working is that you're trying to create an invalid model before actually testing it for validity. What you want to do is to create a valid model, change something and check that it is invalid, like this:

it "is invalid without email" do 
  user = Factory(:user)
  user.email = nil
  user.should_not be_valid
end

I personally like to define my model in a before block, set is as the subject and then change attributes in each spec and check for validity, like this:

before do
  @user = FactoryGirl.create(:user)
end

subject { @user }

it "is invalid without email" do
  subject.email = nil
  should_not be_valid
end

For the record, if you wanted to test that the record creation raised an error (which is definitely not the advisable way to do this), you could do it by wrapping the Factory call in a lambda, like this:

lambda {
    Factory(:user, :email => nil)
}.should raise_error(ActiveRecord::RecordInvalid)
like image 183
Chris Salzberg Avatar answered Nov 20 '25 13:11

Chris Salzberg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!