17

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.

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

How can I stub method_two when it is called within method_one?

Harry
  • 1,659
  • 5
  • 19
  • 34
  • what do you expect from this module? to be a mixin or to call method from it at class level like: `SomeModule.foo` ? – apneadiving Aug 20 '13 at 12:19
  • 2
    Take heart, George. Downvotes on questions are a generally bad idea, in my opinion, but the good news is that inappropriate ones frequently stimulate countervailing upvotes, with a net rep win for you and no net vote impact. – Peter Alfvin Aug 20 '13 at 13:53
  • In addition to @apneadving's question, it's not clear what the relationship of the module to the controller in the code you're trying to test. Also, it's not clear to me what passing a class name to `shared_examples_for` does, as I've only seen a string used as an argument in the documentation as a way to invoke it. – Peter Alfvin Aug 20 '13 at 14:15
  • 2
    In any event, if your controller mixes in that module, you need to stub the controller instance methods, not the module class method as you've tried to do. – Peter Alfvin Aug 20 '13 at 14:17

2 Answers2

5
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?

This approach works for me

Community
  • 1
  • 1
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
kristinalim
  • 3,459
  • 18
  • 27