是否可以
告诉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-mock 回退到原始方法?
可以
缓存原始方法,并显式调用它:
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)