【问题标题】:Falling back to original method in rspec-mocks回退到 rspec-mocks 中的原始方法
【发布时间】:2012-09-21 18:34:25
【问题描述】:

是否可以告诉 RSpec::Mocks 为一组值存根一个方法,否则回退到原始方法?例如:

File.stub(:exist?).with(/txt/).and_return(true)
File.exist? 'log.txt'    # returns true
File.exist? 'dev.log'    # <<< need to fallback to original File.exist? here

目前上例中的最后一次调用会引发MockExpectationError,要求提供默认值。是否可以指示 rspec-mocks 回退到原始方法?

【问题讨论】:

标签: ruby rspec mocking stub


【解决方案1】:

可以缓存原始方法,并显式调用:

original_method = File.method(:exist?)
File.stub(:exist?).with(anything()) { |*args| original_method.call(*args) }
File.stub(:exist?).with(/txt/).and_return(true)

但是,这太麻烦了。希望能看到更好的答案。

为了完整起见,这里对上面的代码做一个概括:

def stub_with_fallback(obj, method)
  original_method = obj.method(method)
  obj.stub(method).with(anything()) { |*args| original_method.call(*args) }
  return obj.stub(method)
end

# usage example:
stub_with_fallback(File, :exist?).with(/txt/).and_return(true)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多