Only stub method when it is called with specific parameters.

1,175 views
Skip to first unread message

Garrett Hart

unread,
Oct 22, 2014, 12:28:26 PM10/22/14
to mocha-d...@googlegroups.com
I am trying to write a stub for a method called #alters? that takes two symbols as parameters and then returns true or false. I would like Mocha to stub  #alters? only when it is called with the parameters :line and :business. When it is called with some other parameters such as :line and :carrier I would like it to not stub the method. Below is my attempt to do that. The stubbed/first call to activity.alters?(:line, :business) returns true as expected. The second call with parameters I don't want stubbed, activity.alters?(:line, :carrier), raises an unexpected invocation. Any thoughts on how to do this? Thank you for your time.

 test "Foo." do
    activity = Activity.new # Activity has an #alters? method on it that takes two symbols.
    # First test that the #alters? method is not stubbed.
    refute activity.alters?(:line, :business)
    refute activity.alters?(:line, :carrier)
    # Attempt to stub #alters? so that when the specific parameters :line and :business are passed in it returns true.
    # Calls to other parameter combinations should still return false.
    activity.stubs(:alters?).with(:line, :business).returns(true)
    # Now test that it is only stubbed for the parameter combination of :line, :business
    assert activity.alters?(:line, :business) # Passes.
    refute activity.alters?(:line, :carrier)  # Raises:
                                              # unexpected invocation: #<Activity:0x7fc6fdda40f0>.alters?(:line, :carrier)
                                              # satisfied expectations:
                                              # - allowed any number of times, invoked once: #<Activity:0x7fc6fdda40f0>.alters?(:line, :business)
  end

floehopper

unread,
Nov 1, 2014, 7:08:59 AM11/1/14
to mocha-d...@googlegroups.com
Hi Garrett,

When you stub a method, the original method implementation is temporarily replaced with a stub implementation. So you have to set up stub behaviour for *all* scenarios i.e. you cannot depend on the original implementation any more. One way to achieve what you want would be to do:

    activity.stubs(:alters?).returns(false)
    activity.stubs(:alters?).with(:line, :business).returns(true)

I hope that helps.

Regards, James.

Garrett Hart

unread,
Nov 10, 2014, 4:05:56 PM11/10/14
to mocha-d...@googlegroups.com
Thank you James. That worked.
Reply all
Reply to author
Forward
0 new messages