Module: MicroMock

Defined in:
lib/micro_mock.rb,
lib/micro_mock/version.rb

Overview

MicroMock is a tiny mocking script.

It doesn’t make any assumptions about the testing framework. It leaves assertions/expectations up to you.

Calling it a mocking script is a bit of a misnomer since its really a dynamic class generator.

The term “stub” is used loosely since it adds real behavior… and “mocking” a class with real behavior proves to be quite useful.

Of course you wouldn’t normally test the mock itself… rather the code that uses the mock. I’ll work on adding some real world examples.

@ example

Mock with a superclass.
Mock = MicroMock.make(Array)
list = Mock.new
list << 1
list.stub :say_hi do |name|
  "Hi #{name}!"
end
list.say_hi "Nate" # => "Hi Nate!"

Examples:

# mock a class method
Mock = MicroMock.make
Mock.stub(:foo) { true }

# make assertions
assert Mock.foo # Test::Unit
Mock.foo.should be_true # RSpec

# mock an instance method
m = Mock.new
m.stub(:bar) { false }

# make assertions
assert_equal false, m.bar # Test::Unit
m.bar.should eq false # RSpec

# setup mock internal behavior
count = 1
m.stub(:a) { count += 1 }
m.stub(:b) { |i| self.a if i > 5 }

# make assertions
10.times { |i| m.b(i) }
assert_equal 5, count # Test::Unit
count.should eq 5 # RSpec

Constant Summary collapse

VERSION =
"0.0.5"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.make(superclass = nil) ⇒ Object

Defines a mock class.



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/micro_mock.rb', line 64

def self.make(superclass=nil)
  if superclass
    klass = Class.new(superclass) do
      def initialize(*args)
        @args = args
        super
      end
    end
  else
    klass = Class.new do
      def initialize(*args)
        @args = args
      end
    end
  end
  klass.extend MicroMock
  klass.send :include, MicroMock
  def klass.initialize(*args)
    super
  end
  Object.const_set "MicroMock#{klass.object_id}", klass
  klass
end

Instance Method Details

#stub(name) { ... } ⇒ Object

Stubs a method. The term stub is used loosely since it adds real functionality.

Parameters:

  • name (Symbol)

    The name of the method.

Yields:

  • The block that will serve as the method definition.



57
58
59
60
61
# File 'lib/micro_mock.rb', line 57

def stub(name, &block)
  context = class << self; self; end if is_a? Class
  context ||= self.class
  context.send :define_method, name, &block
end