【问题标题】:How to avoid deprecation warning for stub_chain in RSpec 3.0?如何避免 RSpec 3.0 中 stub_chain 的弃用警告?
【发布时间】:2013-11-28 22:16:46
【问题描述】:

当我使用 stub_chain 运行测试时,我会收到弃用警告。

describe "stubbing a chain of methods" do
  subject { Object.new }

  context "given symbols representing methods" do
    it "returns the correct value" do
      subject.stub_chain(:one, :two, :three).and_return(:four)
      expect(subject.one.two.three).to eq(:four)
    end
  end
end

弃用警告: 不推荐使用 rspec-mocks 的旧 :should 语法中的 stub_chain 而不显式启用该语法。改用新的:expect 语法或显式启用:should

如何避免这个警告?

【问题讨论】:

    标签: ruby-on-rails rspec


    【解决方案1】:

    为了消除代码原样的警告,您必须在配置中显式启用should 语法:

    RSpec.configure do |config|
      config.expect_with :rspec do |c|
        c.syntax = [:should, :expect]
      end
    end
    

    stub_chain 的替换语法是:

    allow(object).to receive_message_chain(:one, :two, :three).and_return(:four)
    expect(object.one.two.three).to eq(:four)
    

    有关此内容及其用法的更多信息:

    在撰写本文时,对 receive_message_chain 的更改将包含在 rspec-mocks 的 3.0.0.beta2 版本中(请参阅 Changelog)。如果你想要它现在,你必须生活在最前沿,并在你的 Gemfile 中添加特定的提交引用以使 receive_message_chain 工作:

    gem 'rspec-mocks', github: 'rspec/rspec-mocks', ref: '4662eb0'
    

    不幸的是,这实际上并没有回答您关于摆脱弃用消息的问题,我无法做到这一点,即使使用 rspec-mocks 的预发布版本和
    c.syntax = [:should, :expect] 在我的RSpec 配置。

    所以,我会说你的选择是要么等到3.0.0.beta2 发布,然后看看弃用通知是否在你现有的代码中得到修复,或者引入最新的更改并将你的语法更改为receive_message_chain

    具体解决方法请见Myron's answer

    【讨论】:

    • 你用stub_chain试过这个吗?即使明确启用了:should,警告仍然存在于github上标记为v3.0.0.beta1的版本,我认为它是最新的。
    • 好收获。它不适用于v3.0.0.beta1,我将编辑我的答案。
    【解决方案2】:
    RSpec.configure do |config|
      config.mock_with :rspec do |c|
        c.syntax = [:should, :expect]
      end
    end
    

    请注意,它设置的是 rspec-mocks 语法,而不是 rspec-expectations 语法,正如 Paul 的回答所示。

    【解决方案3】:

    这是一个对我有用的解决方案 - 我使用的是 Rails 4.1.7:

    在 spec/spec_helpber.rb 中,设置 rspec-expectations 和/或 rspec-mocks 的语法如下:

    RSpec.configure do |config|
      config.mock_with :rspec do |mocks|
        mocks.syntax = [:should, :expect]
      end
      config.expect_with :rspec do |expectations|
        expectations.syntax = [:should, :expect]
      end
    end
    

    希望这对其他人有帮助:)

    【讨论】:

      【解决方案4】:

      对于任何想要将旧项目升级到新语法的人,有一个工具here

      正如Relish blog 中提到的,他们将来可能会将 should 语法移到外部 gem 中,这让我相信它最终会被淘汰。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-11
        • 2019-02-21
        • 1970-01-01
        • 2016-12-25
        • 2021-02-04
        • 2022-01-04
        相关资源
        最近更新 更多