Injecting mocks (the Mocha way)

I thought I’d compare and contrast the way Kevin Clark was injecting mocks and how you can do it with Mocha.

Kevin Clark’s way

def test_process_exit
  delegate_methods_to_mock!(RailsFCGIHandler, :close_connection) do
    fcgi = flexmock()
    fcgi.should_receive(:close_connection)
    @handler.mock = fcgi
    @handler.stubs(:when_ready).returns(:exit)
    @handler.process!
  end
end

Using Mocha

def test_process_exit
  @handler.expects(:close_connection)
  @handler.stubs(:when_ready).returns(:exit)
  @handler.process!
end

I think it’s a bit more readable and you don’t need the block construction which starts becoming a nuisance when you need to stub methods on multiple classes.