开发者

Mocking Sort With Mocha

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 in开发者_如何学Cvoked: [ 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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜