Module: Cuprum::Utils::InstanceSpy

Defined in:
lib/cuprum/utils/instance_spy.rb

Overview

Utility module for instrumenting calls to the #call method of any instance of a command class. This can be used to unobtrusively test the functionality of code that calls a command without providing a reference to the command instance, such as chained commands or methods that create and call a command instance.

Examples:

Observing calls to instances of a command.

spy = Cuprum::Utils::InstanceSpy.spy_on(CustomCommand)

expect(spy).to receive(:call).with(1, 2, 3, :four => '4')

CustomCommand.new.call(1, 2, 3, :four => '4')

Observing calls to a chained command.

spy = Cuprum::Utils::InstanceSpy.spy_on(ChainedCommand)

expect(spy).to receive(:call)

Cuprum::Command.new {}.
  chain { |result| ChainedCommand.new.call(result) }.
  call

Block syntax

Cuprum::Utils::InstanceSpy.spy_on(CustomCommand) do |spy|
  expect(spy).to receive(:call)

  CustomCommand.new.call
end # spy_on

Defined Under Namespace

Classes: Spy

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.clear_spiesObject

Retires all spies. Subsequent calls to the #call method on command instances will not be mirrored to existing spy objects.


43
44
45
46
47
# File 'lib/cuprum/utils/instance_spy.rb', line 43

def clear_spies
  Thread.current[:cuprum_instance_spies] = nil

  nil
end

.spy_on(command_class) ⇒ Cuprum::Utils::InstanceSpy::Spy .spy_on(command_class) {|Cuprum::Utils::InstanceSpy::Spy| ... } ⇒ nil

Note:

Calling this method for the first time will prepend the Cuprum::Utils::InstanceSpy module to Cuprum::Command.

Finds or creates a spy object for the given module or class. Each time that the #call method is called for an object of the given type, the spy's #call method will be invoked with the same arguments and block.

Overloads:

Parameters:

  • command_class (Class, Module)

    The type of command to spy on. Must be either a Module, or a Class that extends Cuprum::Command.

Raises:

  • (ArgumentError)

    If the argument is neither a Module nor a Class that extends Cuprum::Command.


71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/cuprum/utils/instance_spy.rb', line 71

def spy_on command_class
  guard_spy_class!(command_class)

  instrument_call!

  if block_given?
    begin
      instance_spy = assign_spy(command_class)

      yield instance_spy
    end # begin-ensure
  else
    assign_spy(command_class)
  end # if-else
end

Instance Method Details

#call(*args, &block) ⇒ Object


132
133
134
135
136
# File 'lib/cuprum/utils/instance_spy.rb', line 132

def call *args, &block
  Cuprum::Utils::InstanceSpy.send(:call_spies_for, self, *args, &block)

  super
end