【问题标题】:Stubbing method for one argument, call original for other一个参数的存根方法,其他参数调用原始方法
【发布时间】:2012-11-27 17:27:47
【问题描述】:

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

@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

但是,当调用解析方法时,这不起作用,它在我的解析方法的f = open(mypath).read 行中返回"NoMethodError: undefined method read for nil:NilClass"

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

如果有任何建议和提示,我会很高兴 :)

【问题讨论】:

    标签: ruby-on-rails rspec mocking stub


    【解决方案1】:

    question非常相似

    这应该可以工作

    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
    

    【讨论】:

    • 感谢您指出另一个问题 - 我认为我的错误是由于“do |arg|”之前的微妙“.with”,它没有返回任何返回值。现在它对我有用(我使用@s.should_receive(:open).at_least(:once) do |arg|
    【解决方案2】:

    您是否考虑过使用fakeweb gem?我相信它修补了 Net::HTTP,OpenURI 的 open 方法包装了它。

    FakeWeb.register_uri(:get, "http://stackoverflow.com/questions", :body => File.open(TESTFILE, "r"))
    

    【讨论】:

    • 感谢您的提示,从长远来看,随着测试套件的进展,我想这是一个很好的方法(抱歉,投票的分数太少了)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多