如何使用RSpec存根Ruby类中的私有方法?
- 内容介绍
- 文章标签
- 相关推荐
本文共计229个文字,预计阅读时间需要1分钟。
我尝试使用RSpec 3创建一个外部请求获取某些JSON的方法。之前我将它放在`spec_helper.rb`文件中,但现在我将方法移动到自己的类中,但发现不再有效。`RSpec.configure do |config| config.before do`
我试图使用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相同并尝试将存根放在实际规范之前,但仍在进行外部请求.
您的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
本文共计229个文字,预计阅读时间需要1分钟。
我尝试使用RSpec 3创建一个外部请求获取某些JSON的方法。之前我将它放在`spec_helper.rb`文件中,但现在我将方法移动到自己的类中,但发现不再有效。`RSpec.configure do |config| config.before do`
我试图使用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相同并尝试将存根放在实际规范之前,但仍在进行外部请求.
您的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

