Strict, ordered mock objects using very lightweight syntax in your tests.


The basic procedure for using Hardmock in your tests is:

  • require 'hardmock' (this happens automatically when being used as a Rails plugin)

  • Create some mocks

  • Setup some expectations

  • Execute the target code

  • Verification of calls is automatic in =teardown=

The expectations you set when using mocks are strict and ordered. Expectations you declare by creating and using mocks are all considered together.

  • Hardmock::Mock#expects will show you more examples

  • Hardmock::SimpleExpectation will teach you more about expectation methods


create_mocks :garage, :car

# Set some expectations
@car.expects.drive(:reverse, 5.mph)

# Execute the code (this code is usually, obviously, in your class under test)
@car.start :choke
@car.drive :reverse, 5.mph

verify_mocks # OPTIONAL, teardown will do this for you

Expects @garage.open_door, @car.start(:choke) and @car.drive(:reverse, 5.mph) to be called in that order, with those specific arguments.

  • Violations of expectations, such as mis-ordered calls, calls on wrong objects, or incorrect methods result in Hardmock::ExpectationError

  • verify_mocks will raise VerifyError if not all expectations have been met.

Download and Install

  • Homepage: hardmock.rubyforge.org

  • GEM or TGZ or ZIP: rubyforge.org/frs/?group_id=2742

  • Rails plugin: script/plugin install

  • SVN access: svn co svn://rubyforge.org/var/svn/hardmock/trunk

  • Developer SVN access: svn co svn://developername@rubyforge.org/var/svn/hardmock/trunk

Setup for Test::Unit

require 'hardmock'
require 'assert_error' # OPTIONAL: this adds the TestUnit extension 'assert_error'

NOTE: If installed as a Rails plugin, init.rb does this for you… nothing else is needed.

Setup for RSpec

Get this into your spec helper or environment or Rakefile or wherever you prefer:

Spec::Runner.configure do |configuration|
  configuration.include Hardmock
  configuration.after(:each) {verify_mocks}

This puts the implicit conveniences into your spec context, like “create_mocks” etc, and also provides for automatic “verify_mocks” after each Example is run.