如何 rspec 模拟 open-uri? [英] How to rspec mock open-uri?

查看:46
本文介绍了如何 rspec 模拟 open-uri?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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")

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

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")

但我不断收到此错误

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

推荐答案

我以为open方法是在Kernel的层面上定义的,但是我错了.

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

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

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

这篇关于如何 rspec 模拟 open-uri?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆