Patrick Patrick - 2 months ago 14
Ruby Question

RSpec - unable to stub class private method

I am trying to stub out the method that makes an external request for some JSON using RSpec 3. I had it working before by placing this into the

spec_helper.rb
file, but now that I refactored and moved the method into it own class, the stub no longer works.

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


the class looks like this

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


Despite keeping the
spec_helper.rb
the same and trying to place the stub right before the actual spec, an external request is still being made.

Answer

Your request_url method is an instance and not a class method, therefore you have to write:

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