Rspec - 存根模块方法

Har*_*rry 15 rspec ruby-on-rails mocking

如何在模块中存根方法:

module SomeModule
    def method_one
        # do stuff
        something = method_two(some_arg)
        # so more stuff
    end

    def method_two(arg)
        # do stuff
    end
end
Run Code Online (Sandbox Code Playgroud)

我可以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
Run Code Online (Sandbox Code Playgroud)

其中的规范SomeModule包含在SomeController失败中,因为method_two抛出异常(它尝试进行未播种的数据库查找).

method_two在内部调用时如何存根method_one

小智 5

allow_any_instance_of(M).to receive(:foo).and_return(:bar)
Run Code Online (Sandbox Code Playgroud)

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

这种方法对我有用


kri*_*lim 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
Run Code Online (Sandbox Code Playgroud)

  • 请尝试对正在发生的事情以及背后的原因进行一些解释。 (18认同)