I’m working on a little pet Rails project and wanted to use Mocha to isolate my controller tests a little from what is usually encouraged, especially in light of what happened last time. I figured I’d give Mocha a go.
I wanted to verify that my service was called with objects that look equal to what I was expecting. Ordinarily, it will compare instances - are they the same object. I didn’t want that, but rather wanted to test that the values of my (ActiveRecord) objects were the equal. Easy. Mocha allows with
to be called with a block that is evaluated to compare the objects.
My tests look something like this
def test_should_ask_service_to_calculate_new_prices_for_booking address = Address.new(:postcode => "W1 1QE") booking = create_booking OrderBookingService.expects(:calculate_price).with(booking, address) do |b, a| b.attributes == booking.attributes && a.attributes == address.attributes end post :calculate_price, :booking => booking, :collection_address => addressend
It’s something I’ve had to do many times in the past with JMock and NMock - I want to test equality for an aspect of some other object but it’s always meant writing rather a lot of code. Neat.