Mocha: stubbing method with specific parameter but

2020-03-11 10:46发布

问题:

I want to stub a method with Mocha only when a specific parameter value is given and call the original method when any other value is given.

When I do it like this:

MyClass.any_instance.stubs(:show?).with(:wanne_show).returns(true)

I get an

unexpected invocation for MyClass.show?(:other_value)

I also know, that I can stub all parameters when writing the mock without the ´with´-call and then give my specific mock. But then I have to know the return value for every call, which is not the case :/

tldr; Is there a way to call the original method in a stub or to stub just specific parameters and leave the others?

回答1:

The answer depends on what exactly you're testing.

A few notes:

1) I always avoid using stubs.any_instance. You can be specific in your stubs/mocks, which prevents false testing positives.

2) I prefer using spies along with stubs, to actively assert that something has been called. We use the bourne gem for this purpose. The alternative is to use a mock, which implicitly tests if something is being called (e.g. will fail if it doesn't get called.

So your class-method might looks something like this (note, this is RSpec syntax):

require 'bourne'
require 'mocha'

it 'calls MyClass.show?(method_params)' do
  MyClass.stubs(:show?)

  AnotherClass.method_which_calls_my_class

  expect(MyClass).to have_received(:show?).with('parameter!')
end

class AnotherClass
  def self.method_which_calls_my_class
    MyClass.show?('parameter!')
  end
end

There are a lot of stub/spy examples here.

Hope this helps.