Mocha: stubbing method with specific parameter but not for other parameters

后端 未结 1 1560
予麋鹿
予麋鹿 2021-01-11 14:13

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:

1条回答
  •  孤街浪徒
    2021-01-11 14:45

    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.

    0 讨论(0)
提交回复
热议问题