如何在模块中存根方法:
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
。
我想通过存根method_one
的返回值来孤立地测试method_two
:
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
SomeModule
中包含的SomeController
中的规范失败,因为method_two
抛出异常(它尝试执行未播种的数据库查找)。
如何在method_two
内调用method_one
时隐藏{{1}}?
答案 0 :(得分:3)
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
答案 1 :(得分:3)
allow_any_instance_of(M).to receive(:foo).and_return(:bar)
Is there a way to stub a method of an included module with Rspec?
这种方法对我有用