Upgrade to rspec 3 cause error when using should have(1).error_on
Asked Answered
R

3

12

Since I updated my Gemfile and moved to rspec 3, in many tests, I'm getting a error for: way:

it "should reject attribute that are too short" do
      short = "a" * 3
      hash = @attr.merge(:details => short)
      Deal.new(hash).should have(1).error_on(:details)
    end

I'm getting this error:

Failure/Error: Deal.new(hash).should have(1).error_on(:details)
     NoMethodError:
       undefined method `have' for #<RSpec::ExampleGroups::Deal_2::TestsOnDealsModelsValidations>

I read I should now be using "expect" instead of should but here with have(1).error_on, how should I write it to comply with rspec 3?

I tried the following but it still does not work:

it "should reject attribute that are too short" do
      short = "a" * 3
      hash = @attr.merge(:details => short)
      expect(Deal.new(hash).error_on(:details).size).to eq(1)
    end
Repentance answered 7/6, 2014 at 10:32 Comment(0)
C
18

I have replaced the likes of

Deal.new(hash).should have(1).error_on(:details)

with

deal = Deal.new(hash)
expect(deal.valid?).to be_falsey
expect(deal.errors[:details].size).to eq(1)

The first expectation with valid? is necessary as it initializes the errors list.

Craps answered 16/7, 2014 at 19:43 Comment(0)
P
8

have and other similar matchers have been moved out of rspec core and into another gem, rspec-collection-matchers.

I recommend following the upgrade path from rspec 2 -> 3 as detailed in the rspec docs: https://relishapp.com/rspec/docs/upgrade

  • Upgrade to rspec 2.99
  • Run your test suite
  • Fix deprecation warnings
  • Upgrade to rspec 3.

If you had done this you would have received a deprecation error with your code that would have also told you what to do to fix it.

Piliferous answered 7/6, 2014 at 10:50 Comment(1)
Just add in your Gemfile: gem "rspec-collection-matchers".Whitefish
D
1

The line to add to your Gemfile should be:

gem 'rspec-collection_matchers'
Dagoba answered 15/10, 2015 at 16:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.