【问题标题】:How to rspec mock open-uri?如何rspec模拟open-uri?
【发布时间】:2012-05-29 10:05:28
【问题描述】:

我有这个简单的代码,用于发送 http 请求并读取所有响应。 这是我的 Rails 代码

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

如何为这行代码编写规范。我没有使用 mocha 和 webmock 的选项。我只能使用 Rpsec 的 mocking 框架。

我已经尝试过使用这个语句

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

但我不断收到此错误

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

【问题讨论】:

    标签: rspec-rails


    【解决方案1】:

    我以为open方法是在Kernel的层次上定义的,结果我错了。

    如果您想模拟open,您应该在对象的级别上这样做:

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

    【讨论】:

    • 这很好,你可以使用 expect(object_under_test).to receive(:open).with(anything).and_return(File.read(File.new(Rails.root.join("spec /fixtures/images/sample.jpeg")))) 在测试期间存根 S3 文件读取。
    【解决方案2】:

    我做到了:

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

    【讨论】:

    • @Brian 重新格式化如何?你想扩展什么?像这样使用stub_chain 意味着你可以在my_object 中调用open("whatever").read,你会得到"my_return_value"
    • 你是对的。当我审查它时,您的答案被归类为“低质量”(因为它的长度)。那天晚上晚些时候我做了一些研究,结果证明你的答案是正确的(尽管很简洁)。我已删除评论并对您的回答 +1。对不起,先生!
    • 在 Rspec 3.3.1 中使用 stub_chain 时收到弃用警告。新的 :expect 语法是什么?
    【解决方案3】:

    根据此链接http://distillations.2rye.com/2011/08/mock-the-web-openuri/,open 函数是在内核模块上定义的,但混合到您的控制器中。因此,您需要在该级别存根调用。此解决方案适用于 RSpec 控制器测试:

      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】:

      要存根open-uri,您可以使用此语法RSpec 3+

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

      【讨论】:

        猜你喜欢
        • 2010-10-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-06
        • 2012-12-10
        • 1970-01-01
        相关资源
        最近更新 更多