Optional Parameters in Mocha

One of the new features added in Mocha 0.9 is the ability to specify the values of optional parameters without requiring them to be present. Some examples should make this clearer…

Let’s assume we’re trying to set up an expectation for the invocation of a method which has some parameters with default values…

def my_method(one, two, three = 3, four = 4)
  # implementation

We can use the new Mocha::ParameterMatchers#optionally method within the call to Expectation#with as follows…

object = mock('object')
object.expects(:my_method).with(1, 2, optionally(3, 4))

This specifies that we are expecting an invocation of my_method. As usual, the first two required parameters (one & two) must have values 1 & 2 respectively. However, the last two optional parameters (three & four) only have to have the values 3 & 4 respectively if they are supplied.

So any of the following invocations would satisfy the expectation…

object.my_method(1, 2)
object.my_method(1, 2, 3)
object.my_method(1, 2, 3, 4)

Whereas none of the following invocations would satisfy the expectation and an error would be raised…

object.my_method(1, 3)
object.my_method(1, 2, 4)
object.my_method(1, 2, 4, 4)
object.my_method(1, 2, 3, 5)