Ruby on rails 一个参数的stubing方法,另一个参数调用original

Ruby on rails 一个参数的stubing方法,另一个参数调用original,ruby-on-rails,rspec,mocking,stub,Ruby On Rails,Rspec,Mocking,Stub,对于测试期间的API调用,我希望对OpenURI open方法进行存根,以返回一个文件,该文件的内容以常量形式打包。但是,在相同的解析方法中,对openuriopen的所有其他调用都应该正常处理 @obj.should_receive(:open).with do |arg| if arg == mypath # mypath is a string constant like "http://stackoverflow.com/questions" obj=double("obje

对于测试期间的API调用,我希望对OpenURI open方法进行存根,以返回一个文件,该文件的内容以常量形式打包。但是,在相同的解析方法中,对openuriopen的所有其他调用都应该正常处理

@obj.should_receive(:open).with do |arg|
  if arg == mypath # mypath is a string constant like "http://stackoverflow.com/questions"
    obj=double("object_returned_by_openuri_open") # create a double
    obj.stub(:read).and_return(TESTFILE) # with a stub
    obj #return the double
  else
    open(arg) # call original Open URI method in all other cases
  end
end
但是,当调用解析方法时,这不起作用,它返回
“NoMethodError:
在
f=open(mypath)行中为nil:NilClass“
读取未定义的方法。读取我的解析方法的

有人知道如何实现这种“部分方法存根”(为一个特定参数存根一个方法,为其他参数调用original)吗。其他文件是图像,所以我不想在源代码中将它们作为常量存储。为了使测试独立于网络,我还可以在
else
案例中返回一个本地图像文件


我很高兴得到任何建议和提示:)

您考虑过使用gem吗?我相信它修补了Net::HTTP,OpenURI的
open
方法封装了它

FakeWeb.register_uri(:get, "http://stackoverflow.com/questions", :body => File.open(TESTFILE, "r"))
与此非常相似

这应该行得通

original_method = @obj.method(:open)
@obj.should_receive(:open).with do |arg|
  if arg == mypath # mypath is a string constant like "https://stackoverflow.com/questions"
   obj=double("object_returned_by_openuri_open") # create a double
   obj.stub(:read).and_return(TESTFILE) # with a stub
   obj #return the double
 else
   original_method.call(arg) # call original Open URI method in all other cases
 end
end

感谢您指出我的另一个问题-我认为我的错误是由于微妙的“.with”在“do | arg |”之前,它没有返回任何返回值。现在它对我有效了(我使用
@s.should_receive(:open)。至少(:once)do | arg |
)谢谢这个提示,我想随着测试套件的进展,从长远来看,这是一个很好的方式(对不起,分数太少,无法投票)