3

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.

Vega
  • 27,856
  • 27
  • 95
  • 103
Reid
  • 661
  • 1
  • 8
  • 25

3 Answers3

1

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.

Kim
  • 1,068
  • 13
  • 25
1

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

Jon Schneider
  • 25,758
  • 23
  • 142
  • 170
0
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
kevinluo201
  • 1,444
  • 14
  • 18