Some fun with Erlang and FlexMock.
Erlang defines functions by listing a set of possible argument lists and the body of the function to be executed for each argument list. For example, the factorial function might be defined in Erlang as:
factorial(0) -> 1;
factorial(N) -> N * fac(N-1).
If factorial is called with a 0 (zero) for an argument, the first argument list will be chosen and the value of the factorial function will be 1. Otherwise, the value returned will be calculated by a recursive call to factorial.
While playing around with FlexMock the other day, I realized that it does parameter matching, much like Erlang, when deciding what mock method to call. So I started wondering if you could write Erlang-like function definitions in FlexMock.
Here’s the result.
mock = flexmock('fact')
mock.should_receive(:factorial).with(0).and_return(1)
mock.should_receive(:factorial).with(Integer).
and_return { |n| n * mock.factorial(n-1) }
Ok, that was fun. But let’s not start building entire systems using nothing but FlexMock.