Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RSpec - unable to stub class private method

Tags:

ruby

rspec

rspec3

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.

like image 839
Patrick Avatar asked Aug 10 '14 03:08

Patrick


1 Answers

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
like image 150
spickermann Avatar answered Oct 01 '22 08:10

spickermann