【问题标题】:Upgrade to rspec 3 cause error when using should have(1).error_on使用 should have(1).error_on 时升级到 rspec 3 会导致错误
【发布时间】:2014-06-07 10:32:55
【问题描述】:

自从我更新了我的 Gemfile 并移至 rspec 3 后,在许多测试中,我收到了以下错误:方式:

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

我收到此错误:

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

我读到我现在应该使用“expect”而不是应该使用 have(1).error_on,我应该如何编写它以符合 rspec 3?

我尝试了以下方法,但仍然无法正常工作:

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

【问题讨论】:

    标签: ruby-on-rails rspec rspec3


    【解决方案1】:

    我已经替换了类似的

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

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

    valid? 的第一个期望是必要的,因为它初始化了 errors 列表。

    【讨论】:

      【解决方案2】:

      have 和其他类似的匹配器已从 rspec 核心移出到另一个 gem,rspec-collection-matchers

      我建议按照 rspec 文档中详细说明的 rspec 2 -> 3 的升级路径:https://relishapp.com/rspec/docs/upgrade

      • 升级到 rspec 2.99
      • 运行您的测试套件
      • 修复弃用警告
      • 升级到 rspec 3。

      如果您这样做了,您的代码会收到一个弃用错误,该错误还会告诉您如何修复它。

      【讨论】:

      • 只需在您的 Gemfile 中添加:gem "rspec-collection-matchers"。
      【解决方案3】:

      添加到Gemfile 的行应该是:

      gem 'rspec-collection_matchers'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-10-26
        • 2022-01-08
        • 1970-01-01
        • 2015-05-15
        • 1970-01-01
        • 2021-03-21
        • 1970-01-01
        相关资源
        最近更新 更多