How to make Ruby Mocha mock only check about one parameter

1.5k views Asked by At

I want to mock this function:

def self.set_segment_info(segment_info, history_record)
  history_record.segment_info = segment_info
end

In my test, I want a mock that only confirms that I called set_segment_info with an expected value. I don't care about what I pass in for history_record.

How would I do this? I tried

SegmentHistoryRecord.expects(:set_segment_info).with(:segment_info => expected_segment_info, :history_record => anything)

But that doesn't work.

3

There are 3 answers

0
kevinluo201 On
SegmentHistoryRecord.expects(:set_segment_info).with() do |param1, param2|
  # change below to your verification for :segment_info
  # and leave param2 doing nothing, the expectation will ignore param2
  param1 == expected_segment_info
end
0
Kim On

I ran into this today and ended up doing something like:

SegmentHistoryRecord.expects(:set_segment_info).with(
   expected_segment_info, 
   anything
)

I find it more readable that the do version and it helped me avoid a rubocop issue with too many parameters.

1
Jon Schneider On

Here's an implementation where, if your function takes a lot of parameters, it's more convenient to specify a value for just the one you care about, instead of for all of them:

expected_segment_info = # ...
SegmentHistoryRecord.expects(:set_segment_info).with() { |actual_parameters| actual_parameters[:segment_info] == expected_segment_info }

(Where, as in the original question, set_segment_info is the function being mocked, and segment_info is the parameter whose value you want to match. Note that the history_record parameter -- and any others that might be present -- don't need to be included.)