简体   繁体   English

Rspec - 存根模块方法

[英]Rspec - stub module method

How can I stub a method within a module: 如何在模块中存根方法:

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

    def method_two(arg)
        # do stuff
    end
end

I can test method_two in isolation fine. 我可以在隔离中测试method_two

I would like to test method_one in isolation too by stubbing the return value of 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

The specs in SomeModule that are included in SomeController fail because method_two throws an exception (it tries to do a db lookup that has not been seeded). SomeController中包含的SomeModule中的规范失败,因为method_two抛出异常(它尝试执行未播种的数据库查找)。

How can I stub method_two when it is called within method_one ? 我怎样才能存根method_two当它被称为内method_one

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
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? 有没有办法用Rspec存根包含模块的方法?

This approach works for me 这种方法对我有用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM