Question

I do the following:

class FakeResponse
  def body
    'access_token=token'
  end
end
Net::HTTP.stub(:get_response).and_return(FakeResponse.new)

This works fine, but I want as well test, what's the requested URL. So I do

url = 'http://google.de'
Net::HTTP.stub(:get_response).with(URI.parse(url)).and_return(FakeResponse.new)

This does not really work, as it's not the same instance of URI. And in fact, I'd just like to test against an instance variable of that URI.

Is there some way to invoke a block or something to do this test with less pain?

Was it helpful?

Solution

You can try this:

original_get_response = Net::HTTP.method(:get_response)
Net::HTTP.stub(:get_response) do |uri|
  (uri.to_s == 'http://google.de') ? FakeResponse.new : original_get_response.call(uri)
end

Looking at the discussions around the addition of and_call_original a year ago, it seems that storing and calling the original method like this is a pretty common (but awkward) idiom. (There may be an original_method call available to you now but I don't have a build handy to test it out.)

Edit: later, I got to a build and tried simply using .with(URI('...')), which worked fine. Unless I've misunderstood the question?

require 'spec_helper'
require 'net/http'

describe :nethttp do
  before :each do
    Net::HTTP.stub(:get_response).and_return('something')
    Net::HTTP.stub(:get_response).with(URI('http://www.google.com')).and_return('something else')
  end

  it { Net::HTTP.get_response(URI('http://www.google.com')).should eql 'something else' }
  it { Net::HTTP.get_response(URI('http://www.google.co.uk')).should eql 'something' }
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top