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:
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.