如何rspec模拟open-uri?

use*_*961 15 rspec-rails

我有这个简单的代码,我发送http请求并读取所有响应.这是我的rails代码

open("http://stackoverflow.com/questions/ask")
Run Code Online (Sandbox Code Playgroud)

如何为这行代码编写规范.我没有选择使用mocha和webmock.我只能使用Rpsec的模拟框架.

我试图使用这个声明

OpenURI.stub!(:open_uri).should_receive(:open).with("http://stackoverflow.com/questions/ask")
Run Code Online (Sandbox Code Playgroud)

但我一直收到这个错误

RSpec::Mocks::MockExpectationError: (#<RSpec::Mocks::MessageExpectation:0xd1a7914>).open("http://stackoverflow.com/questions/ask")
expected: 1 time
received: 0 times
Run Code Online (Sandbox Code Playgroud)

Zso*_*olt 19

我认为该open方法是在级别上定义的Kernel,但我错了.

如果你想嘲笑open,你应该在对象层面上这样做:

it "should do something" do
  object_under_test = ObjectUnderTest.new
  object_under_test.should_receive(:open).with("http://example.org")
end
Run Code Online (Sandbox Code Playgroud)

  • 这很好,你可以使用expect(object_under_test).来接收(:open).with(任何东西).and_return(File.read(File.new(Rails.root.join)"spec/fixtures/images/sample.jpeg "))))在测试期间删除S3文件读取. (2认同)