Class: Matahari::Spy

Inherits:
Object
  • Object
show all
Defined in:
lib/matahari/spy.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name = nil, opts = {}) ⇒ Spy

Returns a new instance of Spy.



5
6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/matahari/spy.rb', line 5

def initialize(name = nil, opts={})
  @subject = opts[:subject]
  @name = name
  @invocations = []
  @stubbed_calls = {}
  class << self
    instance_methods.each do |meth|
      whitelist = [:name, :define_method, :stubs, :passes_on, :method_missing, :record_invocation, :invocations, :has_received?, :object_id, :respond_to?, :respond_to_missing?, :instance_eval, :instance_exec, :class_eval, :__send__, :send, :should, :should_not, :__id__, :__send__]
      next if whitelist.include?(meth) || whitelist.include?(meth.to_sym)
      undef_method(meth)
    end
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(sym, *args, &block) ⇒ Object

Captures the details of any method call and store for later inspection



29
30
31
32
# File 'lib/matahari/spy.rb', line 29

def method_missing(sym, *args, &block)
  record_invocation(sym, args)
  @stubbed_calls[sym].call if @stubbed_calls[sym]
end

Instance Attribute Details

#invocationsObject (readonly)

Returns the value of attribute invocations.



3
4
5
# File 'lib/matahari/spy.rb', line 3

def invocations
  @invocations
end

#nameObject (readonly)

Returns the value of attribute name.



3
4
5
# File 'lib/matahari/spy.rb', line 3

def name
  @name
end

Instance Method Details

#has_received?(times = nil) ⇒ Boolean

Pass an iterator to this method to specify the number of times the method should have been called. E.g. spy.has_received?(3.times). While other iterators might work, the idea is to allow this nice DSL-ish way of asserting on the number of calls, hence the odd method signature.

Returns:

  • (Boolean)


38
39
40
# File 'lib/matahari/spy.rb', line 38

def has_received?(times=nil)
  InvocationMatcher.new(times)
end

#passes_on(sym) ⇒ Object



24
25
26
# File 'lib/matahari/spy.rb', line 24

def passes_on(sym)
  @stubbed_calls[sym] = @subject.method(sym)
end

#stubs(sym, &block) ⇒ Object

When a given method call, sym, is invoked on self, call block and return its result



20
21
22
# File 'lib/matahari/spy.rb', line 20

def stubs(sym, &block)
  @stubbed_calls[sym] = block
end