Jackson Cunningham
Jackson Cunningham

Reputation: 5073

Rspec validation error causing a test to fail (but it's my intention to have a validation error)

Rspec

    context "has non ascii characters" do 

        it "will not call get_imdb" do 
          expect_any_instance_of(Celebrity).not_to receive(:get_imdb)
          FactoryGirl.build(:imdb_celebrity, first_name: "Sæthy")
        end

      end

model:

def celebrity_status

    if full_name.ascii_only?
      get_imdb  ## << -- returns string or nil
    end

   ###  If get_imdb returns nil (or isn't called), record is not valid

end

Validation fails if get_imdb returns nil or isn't called. My problem is that I'm trying to test the ascii characters portion of the method, but by doing that - my validation is failing and giving me a "Validation Failed" error in the console when running Rspec tests.

But that's what I want to happen... I want the validation to fail.

How can I solve this?

Upvotes: 1

Views: 2028

Answers (2)

zetetic
zetetic

Reputation: 47548

By itself, a model validation failure should not raise an exception. You may be attempting to save the record, which would case save to fail, and might raise an exception if called via save! or create!.

You can test whether the model is valid by calling valid?

expect(celebrity.valid?).to be false

It is also useful to check the error hash to see that it has the expected contents:

celebrity.valid? # => false
expect(celebrity.errors[:my_error]).to equal "my error message"

Upvotes: 2

dimakura
dimakura

Reputation: 7655

If you want to test your code on having exceptions, you should use Rspec's raise_errormatcher:

expect { 3 / 0 }.to raise_exception

More info here: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers/raise-error-matcher

Upvotes: 0

Related Questions