How to Make Ruby Mocha Mock Only Check About One Parameter

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 Answers

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.

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

1
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest