Mock

A straightfoward mocking facility. Typically used in test cases. The Mock class offers a few constructors for quickly building mockups.

  mock - Returns a static reponse.
  echo - Returns the arguments passed-in.
  spin - Returns a rotation of responses.
  keys - Returns an index of responses.

Mock classes can be built from sratch or partially framed against other classes.

Usage

  class ContextMock < Mock
    mock :response_headers, {}
    spin :host_url, ['http://www.nitrohq.com','http://www.rubyforge.com']
  end

  ctx = ContextMock.new
  ctx.response_headers['location'] = url
  ctx.host_url   #=> "http://www.nitrohq.com"
  ctx.host_url   #=> "http://www.rubyforge.com"

Or

  class ContextMock < Mock(Context)
    ...
  end
Methods
Constants
UnmockedMethods = %r{^( |inspect |kind_of\?|is_a\?|instance_of\?|class |method|send|respond_to\? |hash |__ )}x
  Certain methods are not mocked:
  inspect       (tricky)
  class         (delegated)
  kind_of?      (delegated)
  is_a?         (delegated)
  instance_of?  (delegated)
  method        (works as-is)
  send          (works as-is)
  respond_to?   (works as-is)
  hash          (no way to mock)

  __id__, __call__, etc. (not meant to be mocked, ever!)
Attributes
[R] mocked_class
Public Class methods
echo( sym )

Responds with input.

# File lib/facets/more/mock.rb, line 108
    def echo( sym )
      define_method( sym ) { |*args| args }
    end
keys( sym, hsh )

Responds according to a mapping of input parameters.

# File lib/facets/more/mock.rb, line 118
    def keys( sym, hsh )
      define_method( sym ) { |*args| hsh[args] }
    end
mock( sym, val )

Mock a static repsonse.

# File lib/facets/more/mock.rb, line 103
    def mock( sym, val )
      define_method( sym ) { |*args| val }
    end
mocks()
# File lib/facets/more/mock.rb, line 98
    def mocks
      self.methods(false)
    end
spin( sym, arr )

Reponds with a rotation of reponses.

# File lib/facets/more/mock.rb, line 113
    def spin( sym, arr )
      define_method( sym ) { |*args| arr.push(arr.shift) ; arr[-1] }
    end