RSpec - unable to stub class private method
Asked Answered
G

1

6

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.

Griseldagriseldis answered 10/8, 2014 at 3:26 Comment(0)
C
14

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
Cascio answered 10/8, 2014 at 3:43 Comment(1)
Thanks! Remove the whitespace from : request_url and I'd happily accept the answerGriseldagriseldis

© 2022 - 2024 — McMap. All rights reserved.