2012-09-21 8 views
1

RSpec :: Mock에 값 세트 에 대한 메소드를 스텁하도록 지정할 수 있습니까? 그렇지 않으면 원래 메소드으로 폴백 하시겠습니까? 예를 들어 : rspec-mock의 원래 메소드로 폴백

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에게 원래의 메소드로 대체하도록 지시 할 수 있습니까?

+0

이이 RSpec에-모의의 문제와 관련되어 완성도를 위해서

, 여기에 위의 코드의 일반화입니다 –

답변

4

일단 원래의 방법을 캐시 수 있고, 명시 적으로 호출

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

그러나,이 너무 복잡합니다. 나는 더 나은 대답을보기를 바랍니다. https://github.com/rspec/rspec-mocks/issues/23

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)