Module: Spy::Mock

Includes:
Base
Defined in:
lib/spy/mock.rb

Overview

A Mock is an object that has all the same methods as the given class. Each method however will raise a NeverHookedError if it hasn't been stubbed. If you attempt to stub a method on the mock that doesn't exist on the original class it will raise an error.

Constant Summary collapse

CLASSES_NOT_TO_OVERRIDE =
[Enumerable, Numeric, Comparable, Class, Module, Object]
METHODS_NOT_TO_OVERRIDE =
[:initialize, :method]

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.new(klass) ⇒ Class

This will create a new Mock class with all the instance methods of given klass mocked out.

Parameters:

  • klass (Class)

Returns:

  • (Class)


41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/spy/mock.rb', line 41

def new(klass)
  mock_klass = Class.new(klass)
  mock_klass.class_exec do
    alias :_mock_class :class
    private :_mock_class

    define_method(:class) do
      klass
    end

    include Mock
  end
  mock_klass
end

Instance Method Details

#initialize(&mock_method) ⇒ Object



11
12
13
# File 'lib/spy/mock.rb', line 11

def initialize(&mock_method)
  Agency.instance.recruit(self)
end

#instance_of?(other) ⇒ Boolean

the only method that doesn't work correctly of a mock if inherited. We overwite for compatibility.

Parameters:

  • other (Class)

Returns:

  • (Boolean)


19
20
21
# File 'lib/spy/mock.rb', line 19

def instance_of?(other)
  other == self.class
end

#method(method_name) ⇒ Method

returns the original class method if the current method is a mock_method

Parameters:

  • method_name (Symbol, String)

Returns:

  • (Method)


26
27
28
29
30
31
32
33
34
# File 'lib/spy/mock.rb', line 26

def method(method_name)
  new_method = super
  parameters = new_method.parameters
  if parameters.size >= 1 && parameters.last.last == :mock_method
    self.class.instance_method(method_name).bind(self)
  else
    new_method
  end
end