Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/css/38.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby RSpec如何打开存根?_Ruby_Testing_Rspec - Fatal编程技术网

Ruby RSpec如何打开存根?

Ruby RSpec如何打开存根?,ruby,testing,rspec,Ruby,Testing,Rspec,我一直在尝试存根open,这是一个开放的uri版本,但我没有成功 我已尝试执行以下操作,但请求仍在继续: Kernel.should_receive(:open).and_return("Whatever for now") 我也试过这样做 OpenURI::OpenRead.should_receive(:open).and_return("Whatever for now") 因为我在OpenURI中找到了HTTP请求的位置 提前感谢您的建议 我建议改用一些东西来存根网络。我认为目前最喜

我一直在尝试存根
open
,这是一个开放的uri版本,但我没有成功

我已尝试执行以下操作,但请求仍在继续:

Kernel.should_receive(:open).and_return("Whatever for now")
我也试过这样做

OpenURI::OpenRead.should_receive(:open).and_return("Whatever for now")
因为我在OpenURI中找到了HTTP请求的位置


提前感谢您的建议

我建议改用一些东西来存根网络。我认为目前最喜欢这样做的是[]。您也可能对rspec感兴趣



唉,我认为FakeWeb可能无法使用
open()
,实际上,它会存根
Net::HTTP
,所以我不确定这是否有效。有没有可能不使用
open()
?:)

在谷歌上花了一段时间后,我在这里找到了一个关于堆栈溢出的解决方案(真不敢相信我以前没有找到这个)

托尼·皮特卢加(Tony Pitluga)的解释(不可链接)

如果在对象的上下文中调用sleep,则应将其存根到对象[…]
关键是,在调用睡眠的上下文中,在任何“自我”上存根睡眠

所以我做了这件事,一切都解决了:

let(:read) { mock('open') }

it "should return the new log-level when the log level was set successfully" do
    read.stub(:read).and_return('log-level set to 1')
    kannel.should_receive(:open).and_return(read)

    kannel.set_log_level(1).should == 1
  end
我就是这么做的

class Gateway

  def do_something
    open('http://example.com').read
  end

end
在我的规范中,我执行以下操作:

describe 'communication' do

  it 'should receive valid response from example.com' do
    gateway = Gateway.new
    gateway.stub_chain(:open, :read).and_return('Remote server response')

    gateway.do_something.should == "Remote server response"
  end 

end

open()我花了更多的时间在谷歌上,发现了另一个帮助我解决的堆栈溢出问题。但是谢谢你的努力!美好的我认为编辑此内容并将其作为
open()
的解决方案发布并接受您自己的答案是合理的。在stubing
open()
时,可能很难找到
sleep()
文章。无论self的上下文是什么,stubing都是一个很好的观点。这帮我解决了一个类似的问题,谢谢!我已经更新了你的代码。这里的解释:我认为这是解决这类问题的好方法。谢谢你提醒我:)还有,
Gateway.any\u instance.stub\u chain(…)