Home

Awesome

Flex Mock -- Making Mocking Easy

FlexMock is a simple, but flexible, mock object library for Ruby unit testing.

Version :: 1.3.1

Links

Installation

You can install FlexMock with the following command.

 $ gem install flexmock

Simple Example

We have a data acquisition class (<code>TemperatureSampler</code>) that reads a temperature sensor and returns an average of 3 readings. We don't have a real temperature to use for testing, so we mock one up with a mock object that responds to the read_temperature message.

Here's the complete example:

  require 'test/unit'
  require 'flexmock/test_unit'

  class TemperatureSampler
    def initialize(sensor)
      @sensor = sensor
    end

    def average_temp
      total = (0...3).collect {
        @sensor.read_temperature
      }.inject { |i, s| i + s }
      total / 3.0
    end
  end

  class TestTemperatureSampler < Test::Unit::TestCase
    def test_sensor_can_average_three_temperature_readings
      sensor = flexmock("temp")
      sensor.should_receive(:read_temperature).times(3).
        and_return(10, 12, 14)

      sampler = TemperatureSampler.new(sensor)
      assert_equal 12, sampler.average_temp
    end
  end

You can find an extended example of FlexMock in Google Example.

Test::Unit Integration

FlexMock integrates nicely with Test::Unit. Just require the 'flexmock/test_unit' file at the top of your test file. The flexmock method will be available for mock creation, and any created mocks will be automatically validated and closed at the end of the individual test.

Your test case will look something like this:

  require 'flexmock/test_unit'

  class TestDog < Test::Unit::TestCase
    def test_dog_wags
      tail_mock = flexmock(:wag => :happy)
      assert_equal :happy, tail_mock.wag
    end
  end

NOTE: If you don't want to automatically extend every TestCase with the flexmock methods and overhead, then require the 'flexmock' file and explicitly include the FlexMock::TestCase module in each test case class where you wish to use mock objects. FlexMock versions prior to 0.6.0 required the explicit include.

RSpec Integration

FlexMock also supports integration with the RSpec behavior specification framework. Starting with version 0.9.0 of RSpec, you will be able to say:

  RSpec.configure do |config|
    config.mock_with :flexmock
  end

  describe "Using FlexMock with RSpec" do
    it "should be able to create a mock" do
      m = flexmock(:foo => :bar)
      m.foo.should === :bar
    end
  end

NOTE: I often can't remember the proper RSpec configuration for flexmock without looking it up. If you are the same, you can put <code>require 'flexmock/rspec/configure'</code> in your spec helper to auto-configure RSpec to use flexmock.

NOTE: Older versions of RSpec used the Spec::Runner for configuration. If you are running with a very old RSpec, you may need the following:

  # Configuration for RSpec prior to RSpec 2.x
  Spec::Runner.configure do |config|
    config.mock_with :flexmock
  end

Quick Reference

Creating Mock Objects

The flexmock method is used to create mocks in various configurations. Here's a quick rundown of the most common options. See FlexMock::MockContainer#flexmock for more details.

NOTE: Versions of FlexMock prior to 0.6.0 used flexstub to create partial mocks. The flexmock method now assumes all the functionality that was spread out between two different methods. flexstub is deprecated, but still available for backward compatibility.

Expectation Declarators

Once a mock is created, you need to define what that mock should expect to see. Expectation declarators are used to specify these expectations placed upon received method calls. A basic expectation, created with the should_receive method, just establishes the fact that a method may (or may not) be called on the mock object. Refinements to that expectation may be additionally declared. FlexMock always starts with the most general expectation and adds constraints to that.

For example, the following code:

    mock.should_receive(:average).and_return(12)

Means that the mock will now accept method calls to an average method. The expectation will accept any arguments and may be called any number of times (including zero times). Strictly speaking, the and_return part of the declaration isn't exactly a constraint, but it does specify what value the mock will return when the expectation is matched.

If you want to be more specific, you need to add additional constraints to your expectation. Here are some examples:

    mock.should_receive(:average).with(12).once

    mock.should_receive(:average).with(Integer).
        at_least.twice.at_most.times(10).
        and_return { rand }

Expectation are always matched in order of declaration. That means if you have a general expectation before a more specific expectation, the general expectation will have an opportunity to match first, effectively hiding the second expectation.

For example:

    mock.should_receive(:average)              # Matches any call to average
    mock.should_receive(:average).with(1).once # Fails because it never matches

In the example, the second expectation will never be triggered because all calls to average will be handled by the first expectation. Since the second expectation is require to match one time, this test will fail.

Reversing the order of the expections so that the more specific expectation comes first will fix that problem.

If an expectation has a count requirement (e.g. once or times), then once it has matched its expected number of times, it will let other expectations have a chance to match.

For example:

    mock.should_receive(:average).once.and_return(1)
    mock.should_receive(:average).once.and_return(2)
    mock.should_receive(:average).and_return(3)

In the example, the first time average is called, the first expectation is matched an average will return 1. The second time average is called, the second expectation matches and 2 is returned. For all calls to average after that, the third expectation returning 3 will be used.

Occasionally it is useful define a set of expecations in a setup method of a test and override those expectations in specific tests. If you mark an expectation with the by_default marker, that expectation will be used only if there are no non-default expectations on that method name. See "by_default" below.

Expectation Criteria

The following methods may be used to create and refine expectations on a mock object. See theFlexMock::Expectation for more details.

    m = flexmock()
    m.should_receive(:any_time)
    m.should_receive(:start).ordered
    m.should_receive(:flip).ordered(:flip_flop_group)
    m.should_receive(:flop).ordered(:flip_flop_group)
    m.should_receive(:end).ordered

Normally ordering is performed only against calls in the same mock object. If the "globally" adjective is used, then ordering is performed against the other globally ordered method calls.

Expectation Actions

Action expectations are used to specify what the mock should do when the expectation is matched. The actions themselves do not take part in determining whether a given expectation matches or not.

    Dog.should_receive(:new).pass_thru { |dog|
      flexmock(dog, :wag => true)
    }

Other Expectation Methods

    m = flexmock.should_receive(:hello).once.and_return("World").mock

NOTE: Using mock when specifying a Demeter mock chain will return the last mock of the chain, which might not be what you expect.

Argument Validation

The values passed to the with declarator determine the criteria for matching expectations. The first expectation found that matches the arguments in a mock method call will be used to validate that mock method call.

The following rules are used for argument matching:

     with(Integer)     will match    f(3)
    with(/^src/)      will match    f("src_object")
    with(/^3\./)      will match    f(3.1415972)
      with(3)         will match    f(3)
      with("hello")   will match    f("hello")
      with(eq(Integer))             will match       f(Integer)
      with(eq(Integer))             will NOT match   f(3)

Note: <em>If you do not use the FlexMock::TestCase Test Unit integration module, or the FlexMock::ArgumentTypes module, you will have to fully qualify the eq method. This is true of all the special argument matches (eq, on, any, hsh and ducktype).</em>

      with(FlexMock.eq(Integer))
      with(FlexMock.on { code })
      with(FlexMock.any)
      with(FlexMock.hsh(:tag => 3))
      with(FlexMock.ducktype(:wag, :bark))
      with(hsh(:run => true))  will match    f(:run => true, :stop => false)
      with(ducktype(:to_str))     will match   f("string")
      with(ducktype(:wag, :bark)) will match   f(dog)
                                  (assuming dog implements wag and bark)
      with(any)             will match       f(3)
      with(any)             will match       f("hello")
      with(any)             will match       f(Integer)
      with(any)             will match       f(nil)
      with(on { |arg| (arg % 2) == 0 } )

will match any even integer.

      m.should_receive(:foo).with(Integer,Proc).and_return(:got_block)
      m.should_receive(:foo).with(Integer).and_return(:no_block)

will cause the mock to return the following:

     m.foo(1) { } => returns :got_block
     m.foo(1)     => returns :no_block

Creating Partial Mocks

Sometimes it is useful to mock the behavior of one or two methods in an existing object without changing the behavior of the rest of the object. If you pass a real object to the flexmock method, it will allow you to use that real object in your test and will just mock out the one or two methods that you specify.

For example, suppose that a Dog object uses a Woofer object to bark. The code for Dog looks like this (we will leave the code for Woofer to your imagination):

  class Dog
    def initialize
      @woofer = Woofer.new
    end
    def bark
      @woofer.woof
    end
    def wag
      :happy
    end
  end

Now we want to test Dog, but using a real Woofer object in the test is a real pain (why? ... well because Woofer plays a sound file of a dog barking, and that's really annoying during testing).

So, how can we create a Dog object with mocked Woofer? All we need to do is allow FlexMock to replace the bark method.

Here's the test code:

  class TestDogBarking < Test::Unit::TestCase
    include FlexMock::TestCase

    # Setup the tests by mocking the +new+ method of
    # Woofer and return a mock woofer.
    def setup
      @dog = Dog.new
      flexmock(@dog, :bark => :grrr)
    end

    def test_dog
      assert_equal :grrr, @dog.bark   # Mocked Method
      assert_equal :happy, @dog.wag    # Normal Method
    end
  end

The nice thing about this technique is that after the test is over, the mocked out methods are returned to their normal state. Outside the test everything is back to normal.

NOTE: <em>In previous versions of FlexMock, partial mocking was called "stubs" and the flexstub method was used to create the partial mocks. Although partial mocks were often used as stubs, the terminology was not quite correct. The current version of FlexMock uses the flexmock method to create both regular stubs and partial stubs. A version of the flexstub method is included for backwards compatibility. See Martin Fowler's article Mocks Aren't Stubs for a better understanding of the difference between mocks and stubs.</em>

This partial mocking technique was inspired by the Stuba library in the Mocha project.

Spies

FlexMock supports spy-like mocks as well as the traditional mocks.

  # In Test::Unit / MiniTest
  class TestDogBarking < Test::Unit::TestCase
    def test_dog
      dog = flexmock(:on, Dog)
      dog.bark("loud")
      assert_spy_called dog, :bark, "loud"
    end
  end

  # In RSpec
  describe Dog do
    let(:dog) { flexmock(:on, Dog) }
    it "barks loudly" do
      dog.bark("loud")
      dog.should have_received(:bark).with("loud")
    end
  end

Since spies are verified after the code under test is run, they fit very nicely with the Given/When/Then technique of specification. Here is the above RSpec example using the rspec-given gem:

  require 'rspec/given'

  describe Dog do
    Given(:dog) { flexmock(:on, Dog) }

    context "when barking loudly" do
      When { dog.bark("loud") }
      Then { dog.should have_received(:bark).with("loud") }
    end
  end

NOTE: <em>You can only spy on methods that are mocked or stubbed. That's not a problem with regular mocks, but normal methods on partial objects will not be recorded.</em>

You can get around this limitation by stubbing the method in question on the normal mock, and then specifying pass_thru. Assuming :bark is a normal method on a Dog object, then the following allows for spying on :bark.

   dog = Dog.new
   flexmock(dog).should_receive(:bark).pass_thru
   # ...
   dog.should have_received(:bark)

Asserting Spy Methods are Called (Test::Unit / MiniTest)

FlexMock provied a custom assertion method for use with Test::Unit and MiniTest for asserting that mocked methods are actually called.

Spy Options

Examples:

    dog = flexmock(:on, Dog)

    dog.wag(:tail)
    dog.wag(:head)
    dog.bark(5)
    dog.bark(6)

    assert_spy_called dog, :wag, :tail
    assert_spy_called dog, :wag, :head
    assert_spy_called dog, {times: 2}, :wag

    assert_spy_not_called dog, :bark
    assert_spy_not_called dog, {times: 3}, :wag

    is_even = proc { |n| assert_equal 0, n%2 }
    assert_spy_called dog, { and: is_even, on: 2 }, :bark, Integer

RSpec Matcher for Spying

FlexMock also provides an RSpec matcher that can be used to specify spy behavior.

Modifiers for have_received

Examples:

    dog = flexmock(:on, Dog)

    dog.wag(:tail)
    dog.wag(:head)

    dog.should have_received(:wag).with(:tail)
    dog.should have_received(:wag).with(:head)
    dog.should have_received(:wag).twice

    dog.should_not have_received(:bark)
    dog.should_not have_received(:wag).times(3)

    dog.bark(3)
    dog.bark(6)
    dog.should have_received(:bark).with(Integer).and { |arg|
      (arg % 3).should == 0
    }
    dog.should have_received(:bark).with(Integer).and { |arg|
      arg.should == 6
    }.on(2)

Mocking Class Object

In the previous example we mocked out the bark method of a Dog object to avoid invoking the Woofer object. Perhaps a better technique would be to mock the Woofer object directly. But Dog uses Woofer explicitly so we cannot just pass in a mock object for Dog to use.

But wait, we can add mock behavior to any existing object, and classes are objects in Ruby. So why don't we just mock out the Woofer class object to return mocks for us.

  class TestDogBarking < Test::Unit::TestCase
    include FlexMock::TestCase

    # Setup the tests by mocking the `new` method of
    # Woofer and return a mock woofer.
    def setup
      flexmock(Woofer).should_receive(:new).
         and_return(flexmock(:woof => :grrr))
      @dog = Dog.new
    end

    def test_dog
      assert_equal :grrrr, @dog.bark  # Calls woof on mock object
                                      # returned by Woofer.new
    end
  end

Mocking Behavior in All Instances Created by a Class Object

Sometimes returning a single mock object is not enough. Occasionally you want to mock every instance object created by a class. FlexMock makes this very easy.

  class TestDogBarking < Test::Unit::TestCase
    include FlexMock::TestCase

    # Setup the tests by mocking Woofer to always
    # return partial mocks.
    def setup
      flexmock(Woofer).new_instances.should_receive(:woof => :grrr)
    end

    def test_dog
      assert_equal :grrrr, Dog.new.bark  # All dog objects
      assert_equal :grrrr, Dog.new.bark  # are mocked.
    end
  end

Note that FlexMock adds the mock expectations after the original new method has completed. If the original version of new yields the newly created instance to a block, that block will get an non-mocked version of the object.

Note that new_instances will accept a block if you wish to mock several methods at the same time. E.g.

      flexmock(Woofer).new_instances do |m|
        m.should_receive(:woof).twice.and_return(:grrr)
        m.should_receive(:wag).at_least.once.and_return(:happy)
      end

Default Expectations on Mocks

Sometimes you want to setup a bunch of default expectations that are pretty much for a number of different tests. Then in the individual tests, you would like to override the default behavior on just that one method you are testing at the moment. You can do that by using the by_default modifier.

In your test setup you might have:

  def setup
    @mock_dog = flexmock("Fido")
    @mock_dog.should_receive(:tail => :a_tail, :bark => "woof").by_default
  end

The behaviors for :tail and :bark are good for most of the tests, but perhaps you wish to verify that :bark is called exactly once in a given test. Since :bark by default has no count expectations, you can override the default in the given test.

  def test_something_where_bark_must_be_called_once
    @mock_dog.should_receive(:bark => "woof").once

    # At this point, the default for :bark is ignored,
    # and the "woof" value will be returned.

    # However, the default for :tail (which returns :a_tail)
    # is still active.
  end

By setting defaults, your individual tests don't have to concern themselves with details of all the default setup. But the details of the overrides are right there in the body of the test.

Mocking Law of Demeter Violations

The Law of Demeter says that you should only invoke methods on objects to which you have a direct connection, e.g. parameters, instance variables, and local variables. You can usually detect Law of Demeter violations by the excessive number of periods in an expression. For example:

     car.chassis.axle.universal_joint.cog.turn

The Law of Demeter has a very big impact on mocking. If you need to mock the "turn" method on "cog", you first have to mock chassis, axle, and universal_joint.

    # Manually mocking a Law of Demeter violation
    cog = flexmock("cog")
    cog.should_receive(:turn).once.and_return(:ok)
    joint = flexmock("gear", :cog => cog)
    axle = flexmock("axle", :universal_joint => joint)
    chassis = flexmock("chassis", :axle => axle)
    car = flexmock("car", :chassis => chassis)

Yuck!

The best course of action is to avoid Law of Demeter violations. Then your mocking exploits will be very simple. However, sometimes you have to deal with code that already has a Demeter chain of method calls. So for those cases where you can't avoid it, FlexMock will allow you to easily mock Demeter method chains.

Here's an example of Demeter chain mocking:

    # Demeter chain mocking using the short form.
    car = flexmock("car")
    car.should_receive( "chassis.axle.universal_joint.cog.turn" => :ok).once

You can also use the long form:

    # Demeter chain mocking using the long form.
    car = flexmock("car")
    car.should_receive("chassis.axle.universal_joint.cog.turn").once.
      and_return(:ok)

That's it. Anywhere FlexMock accepts a method name for mocking, you can use a demeter chain and FlexMock will attempt to do the right thing.

But beware, there are a few limitations.

The all the methods in the chain, except for the last one, will mocked to return a mock object. That mock object, in turn, will be mocked so as to respond to the next method in the chain, returning the following mock. And so on. If you try to manually mock out any of the chained methods, you could easily interfer with the mocking specified by the Demeter chain. FlexMock will attempt to catch problems when it can, but there are certainly scenarios where it cannot detect the problem beforehand.

Examples

Refer to the following documents for examples of using FlexMock:

License

Copyright 2003-2013 by Jim Weirich (jim.weirich@gmail.com). All rights reserved.

Permission is granted for use, copying, modification, distribution, and distribution of modified versions of this work as long as the above copyright notice is included.

Other stuff

See Also

If you like the spy capability of FlexMock, you should check out the rspec-given gem that allows you to use Given/When/Then statements in you specifications.

Warranty

This software is provided "as is" and without any express or implied warranties, including, without limitation, the implied warranties of merchantibility and fitness for a particular purpose.