Making Ruby Bacon play with Mocha

This post is not about pork and coffee. So, stay clear, if google has landed you here thinking I am going to describe some sort of recipe for making nice mocha coffee with chunky bacons.

Its about using shiny new testing library called Bacon by Chris. Mocha is of course, venerable mocking library for Ruby and Rails.Here is a tiny bit of code that will make you started with bacon and mocha:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
require "rubygems"
require "bacon"
require "mocha/standalone"
require "mocha/object"
class Bacon::Context
  include Mocha::Standalone
  alias_method :old_it,:it
  def it description,&block
    mocha_setup
    old_it(description,&block)
    mocha_verify
    mocha_teardown
  end
end

Thats it. Happy baking.

3 thoughts on “Making Ruby Bacon play with Mocha

  1. Rich

    The above script could be improved slightly: as it stands, any mocha errors won’t cause the Bacon test to fail; they’ll just dump the errors to stdout.

    You could refactor it to the following, which avoids this issue:

    class Bacon::Context
    include Mocha::Standalone
    def it_with_mocha description
    it_without_mocha description do
    mocha_setup
    yield
    mocha_verify
    mocha_teardown
    end
    end
    alias_method_chain :it, :mocha
    end

    Reply
  2. Zubin

    Would something like this work?

    # spec_helper.rb
    before(:each) { mocha_setup }
    after(:each) { mocha_verify; mocha_teardown }

    No sure if it would work, but I generally prefer this approach over redefining methods.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *