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

旧街凉风 提交于 2019-12-01 03:15:26

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!