【问题标题】:RSpec - unable to stub class private methodRSpec - 无法存根类私有方法
【发布时间】:2014-08-10 03:26:32
【问题描述】:

我正在尝试使用 RSpec 3 删除对某些 JSON 发出外部请求的方法。我之前通过将其放入 spec_helper.rb 文件中使其工作,但现在我重构并将该方法移动到它自己的类,存根不再工作。

RSpec.configure do |config|
  config.before do
    allow(Module::Klass).to receive(:request_url) do
      JSON.parse(File.read(File.expand_path('spec/fixtures/example_data.json')))
    end
  end
end

这个类看起来像这样

module Module
  class Klass

    # public methods calling `request_url`
    ...

    private

    def request_url(url, header = {})
      request = HTTPI::Request.new
      request.url = url
      request.headers = header

      JSON.parse(HTTPI.get(request).body)
    end
  end
end

尽管保持spec_helper.rb 相同并尝试将存根放在实际规范之前,但仍在发出外部请求。

【问题讨论】:

    标签: ruby rspec rspec3


    【解决方案1】:

    您的request_url 方法是一个实例而不是类方法,因此您必须编写:

    allow_any_instance_of(Module::Klass).to receive(:request_url) do
      JSON.parse(File.read(File.expand_path('spec/fixtures/example_data.json')))
    end
    

    【讨论】:

    • 谢谢!从: request_url 中删除空格,我很乐意接受答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-23
    • 1970-01-01
    • 1970-01-01
    • 2015-08-31
    • 2012-05-19
    相关资源
    最近更新 更多