18

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

4 Answers 4

20

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
1
  • 3
    This is nice and you can use expect(object_under_test).to receive(:open).with(anything).and_return(File.read(File.new(Rails.root.join("spec/fixtures/images/sample.jpeg")))) to stub out an S3 file-read during a test. Dec 29, 2016 at 20:26
4

To stub open-uri you can use this syntax RSpec 3+

file = double('file')
expect(OpenURI).to receive(:open_uri).and_return(file)
2

I did:

my_object.stub_chain(:open, :read) { "my return value" }
3
  • @Brian Re-format how? What would you like expanded? Using stub_chain like this means you can call open("whatever").read within my_object and you'll get "my_return_value" back.
    – Henrik N
    Oct 16, 2013 at 14:33
  • 1
    you are right. Your answer was classified as 'low quality' (because of its length) when I was reviewing it. I did some research later that night and it turns out, your answer is correct (despite the brevity). I have removed the comment and +1'd your answer. My apologies, sir!
    – Brian
    Oct 16, 2013 at 16:50
  • I am getting a deprecation warning when using stub_chain in Rspec 3.3.1. What is the new :expect syntax for this?
    – Epigene
    Dec 14, 2015 at 14:37
2

According to this link http://distillations.2rye.com/2011/08/mock-the-web-openuri/ the open function is defined on the Kernel module, but mixed into your controller. Therefore you need to stub the call at that level. This solution works well for RSpec controller tests:

  html_content = <<-EOS
          <html><head>
           <title>Some Title</title>
          </head>
          <body>Some Content</body></html>
        EOS

  YourController.any_instance.stub(:open).and_return html_content

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.