doub1ejack
doub1ejack

Reputation: 11171

Rspec test fails to show that model requires an email

I'm (mostly) following a tutorial everydayrails.com trying to write a test that shows that my user model requires an email:

 17   it "requires an email" do
 18     user = FactoryGirl.create(:user, email: nil)
 19     expect( user ).to_not be_valid
 20   end

But this fails... because my user model requires an email?

Failures:

  1) User requires an email
     Failure/Error: user = FactoryGirl.create(:user, email: nil)

     ActiveRecord::RecordInvalid:
       Validation failed: Email can't be blank
     # ./spec/models/user_spec.rb:18:in `block (2 levels) in <top (required)>'

What am I doing wrong here?

Upvotes: 1

Views: 37

Answers (3)

Bilawal Hameed
Bilawal Hameed

Reputation: 256

The key things I would recommend when writing tests in the future are:

  • Readable. Tests should be really easy to read (and write).
  • Extensive. Tests shouldn't break unnecessarily and should test exactly what you need it to.

The code example that you'd be looking for is:

context "Email address" do
  it 'does not validate if email is nil' do
    user_with_no_email = build(:user, email: nil)

    expect(user_with_no_email).to receive(:validate).with(false)
    expect(user_with_no_email).to have(1).error_on(:email)
  end
end

Upvotes: 0

Rajarshi Das
Rajarshi Das

Reputation: 12320

You can try this test like this way

it "requires an email" do
  expect(User.new.errors_on(:email)).to include("can't be blank")
end

or

expect(Factory.build(:user, email: nil)).to_not be_valid

More on this Please consult errors_on

Upvotes: 0

Frederick Cheung
Frederick Cheung

Reputation: 84114

Your call to Factory.create runs the validations and internally factory girl uses save! by default so the failed validation will cause an exception to be raised.

Use Factory.build instead (as in the tutorial you link to) to create an unsaved object that you can test for validity

Upvotes: 1

Related Questions