1

How can I mock an array's sort expect a lambda expression?

This is a trivial example of my problem:

# initializing the data
l = lambda { |a,b| a <=> b }
array = [ 1, 2, 3, 4, 5 ]
sorted_array = [ 2, 3, 8, 9, 1]

# I expect that sort will be called using the lambda as a parameter
array.expects(:sort).with( l ).returns( sorted_array )

# perform the sort using the lambda expression
temp = array.sort{|a,b| l.call(a,b) }

Now, at first I expected that this would work; however, I got the following error:

- expected exactly once, not yet invoked: [ 1, 2, 3, 4, 5 ].sort(#<Proc:0xb665eb48>)

I realize that this will not work because l is not passed as a parameter to l. However, is there another way to do what this code is trying to accomplish?

NOTE: I have figured out how to solve my issue without figuring out how to do the above. I will leave this open just in case someone else has a similar problem.

Cheers, Joseph

Vega
  • 27,856
  • 27
  • 95
  • 103
user175750
  • 746
  • 6
  • 5
  • Hi Joseph, I'm bryan. I suspect whether the problem could be cause by "with( l )". With the way you use it, shouldn't sort be called with a param "l"? – Shuo Apr 06 '10 at 23:53
  • Hey Bryan, That makes sense. At first, I assumed that if you provided a code block to .sort, it would pass l to sort. So now I'm looking for another way to do what the above code is trying to do. I have edited the post to specifically include that request. – user175750 Apr 06 '10 at 23:58
  • I see, you've already pointed this out in your original question. :) I'm using a machine where ruby is not installed. Will look at this problem later. Good luck. – Shuo Apr 07 '10 at 00:08

1 Answers1

1

Mocking methods with blocks can be quite confusing. One of the keys is to be clear about what behaviour you want to test. I can't tell from your sample code exactly what it is that you want to test. However, you might find the documentation for Mocha::Expectation#yields (or even Mocha::Expectation#multiple_yields) useful.

James Mead
  • 3,472
  • 19
  • 17