16

如何存根模块中的方法:

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

4

2 回答 2

4
allow_any_instance_of(M).to receive(:foo).and_return(:bar)

有没有办法用 Rspec 存根包含模块的方法?

这种方法对我有用

于 2015-06-11T12:31:51.753 回答
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
于 2013-09-20T18:22:02.870 回答