RSpec - failed to close class with private method

I am trying to stub a method that makes an external request for some JSON using RSpec 3. I worked on this by putting it in a file spec_helper.rb

, but now that I refactored and moved the method into its 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

      

Even though it saves spec_helper.rb

and tries to place the stub right before the actual BOM, the outer query is still running.

+3


source to share


1 answer


Your method request_url

is an instance, not a class method, so you need 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

      

+11


source







All Articles