Rspec - 存根模块方法

时间:2013-08-20 11:26:33

标签: ruby-on-rails rspec 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

我可以单独测试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}}?

2 个答案:

答案 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?

这种方法对我有用