如何在模块中存根方法:
module SomeModule def method_one # do stuff something = method_two(some_arg) # so more stuff end def method_two(arg) # do stuff end end
我可以隔离测试method_two.
我想通过stubbing method_two的返回值来隔离测试method_one:
shared_examples_for SomeModule do it 'does something exciting' do # neither of the below work # SomeModule.should_receive(:method_two).and_return('MANUAL') # SomeModule.stub(:method_two).and_return('MANUAL') # expect(described_class.new.method_one).to eq(some_value) end end describe SomeController do include_examples SomeModule end
SomeController中包含的规范失败,因为method_two抛出一个异常(它尝试做一个未被种子的数据库查找).
在method_one中调用的时候如何存根method_two?
解决方法
shared_examples_for SomeModule do let(:instance) { described_class.new } it 'does something exciting' do instance.should_receive(:method_two).and_return('MANUAL') expect(instance.method_one).to eq(some_value) end end describe SomeController do include_examples SomeModule end