How to rspec mock open-uri?

萝らか妹 提交于 2019-11-28 02:42:31

问题


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

回答1:


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



回答2:


I did:

my_object.stub_chain(:open, :read) { "my return value" }



回答3:


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



回答4:


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

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


来源:https://stackoverflow.com/questions/10796986/how-to-rspec-mock-open-uri

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!