Alex Rivera | Logout

RSpec how to stub open?

Asked 2010-08-30T18:46:48.937
9

I've been trying to stub open, the open-uri version, and I'm not succeeding.

I've tried doing the following but the request keeps going through:

Kernel.should_receive(:open).and_return("Whatever for now")

I've also tried to do

OpenURI::OpenRead.should_receive(:open).and_return("Whatever for now")

Since I tracked down that was where HTTP requests were made in OpenURI.

Thanks in advance for any suggestions!

Edit
Report

2 Answers

13

Here is what I do

class Gateway

  def do_something
    open('http://example.com').read
  end

end

In my spec i do the following:

describe 'communication' do

  it 'should receive valid response from example.com' do
    gateway = Gateway.new
    gateway.stub_chain(:open, :read).and_return('Remote server response')

    gateway.do_something.should == "Remote server response"
  end 

end
answered 2012-05-25T08:58:40.163
1

I'd recommend using something to stub the network instead. I believe the current favorite for doing so is FakeWeb [docs]. You may also be interested in fakeweb-matcher for rspec.


Alas, I think FakeWeb might not work with open(), actually, it stubs Net::HTTP, so I'm not sure if that will work. Any chance of not using open()? :)

answered 2010-08-30T18:58:08.010

Your Answer