Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rspec mock open-uri?

Tags:

rspec-rails

I have this simple code where I am sending http request and reading all the response. Here is my rails code

open("http://stackoverflow.com/questions/ask")

How can I write spec for this line of code. I dont have the option to use mocha and webmock. I can only use mocking framework of Rpsec.

I have tried to use this statement

OpenURI.stub!(:open_uri).should_receive(:open).with("http://stackoverflow.com/questions/ask")

but i keep getting this error

RSpec::Mocks::MockExpectationError: (#<RSpec::Mocks::MessageExpectation:0xd1a7914>).open("http://stackoverflow.com/questions/ask")
expected: 1 time
received: 0 times
like image 429
user1352961 Avatar asked May 29 '12 10:05

user1352961


2 Answers

I thought that the open method is defined on the level of the Kernel, but I was wrong.

If you would like to mock the open, you should do it on the level of your object like this:

it "should do something" do
  object_under_test = ObjectUnderTest.new
  object_under_test.should_receive(:open).with("http://example.org")
end
like image 102
Zsolt Avatar answered Oct 05 '22 12:10

Zsolt


I did:

my_object.stub_chain(:open, :read) { "my return value" }
like image 23
Henrik N Avatar answered Oct 05 '22 13:10

Henrik N