The Flexibility of Mocha

Posted by kev Fri, 01 Sep 2006 18:18:00 GMT

This post just blew me away. Turns out instead of using the delegate_method_to_mock! method I posted the other day, I could use Mocha and just save myself the time. Check this out:

Using Flexmock (and my custom method):

  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

It works but it’s none too pretty. Flexmock people, if there’s a better way speak up.

Here’s the equivalent using Mocha:

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

I can place expectations directly on my object (even though I didn’t create it as a mock) and it takes care of it for me. That is *so* much clearer and I’ve saved 3 lines that didn’t tell me anything new about my test. I think I’m in love.

Posted in , ,  | 3 comments

Comments

  1. Avatar Thorsten said about 13 hours later:

    Mocha looks very cool, but I need some more help. Do you have reference for a tutorial on how to test using mocks and stubs instead of fixtures? Mocha comes with virtually zero documentation, it seems…

  2. Avatar Jim Weirich said 3 days later:

    Flexmock now allows the stubbing of arbitrary objects as well. Unless I misunderstand your example, you can now write:

    def test_process_exit
      flexstub(@handler)should_receive(:close_connection)
      flexstub(@handler).should_receive(:when_ready).once.and_return(:exit)
      @handler.process!
    end

    A bit more verbose than the Stubba syntax, but I agree that its a nice capability to have.

  3. Avatar James Mead said 8 days later:

    Thorsten: I recently overhauled the Mocha documentation and there are some helpful pointers in this article. Let me know if you need some specific help.

Comments are disabled