ruby – RSpec – 无法存根类私有方法

ruby – RSpec – 无法存根类私有方法,第1张

概述我试图使用RSpec 3来创建一个外部请求某些 JSON的方法.我之前将它放在spec_helper.rb文件中,但是现在我重构并将方法移动到它自己的类中,存根不再有效. RSpec.configure do |config| config.before do allow(Module::Klass).to receive(:request_url) do JSON.par 我试图使用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  endend

这个班看起来像这样

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  endend

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

解决方法 您的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
总结

以上是内存溢出为你收集整理的ruby – RSpec – 无法存根类私有方法全部内容,希望文章能够帮你解决ruby – RSpec – 无法存根类私有方法所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1244682.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-07
下一篇 2022-06-07

发表评论

登录后才能评论

评论列表(0条)

保存