Class: Facon::Proxy

Inherits:
Object show all
Extended by:
Forwardable
Defined in:
lib/facon/proxy.rb

Overview

A proxy for mock objects. Stubs and expectations are set on this proxy.

Instance Method Summary collapse

Constructor Details

#initialize(target, name) ⇒ Proxy

Returns a new instance of Proxy.



9
10
11
12
13
14
# File 'lib/facon/proxy.rb', line 9

def initialize(target, name)
  @target, @name = target, name
  @expectations = []
  @stubs = []
  @error_generator = ErrorGenerator.new(target, name)
end

Instance Method Details

#add_expectation(expected_from, method, &block) ⇒ Object



25
26
27
28
29
30
31
# File 'lib/facon/proxy.rb', line 25

def add_expectation(expected_from, method, &block)
  $facon_mocks << (@target) unless $facon_mocks.nil?
  define_expected_method(method)

  @expectations << Expectation.new(@error_generator, @expectation_ordering, expected_from, method, (block_given? ? block : nil), 1)
  @expectations.last
end

#add_negative_expectation(expected_from, method, &block) ⇒ Object



33
34
35
36
37
38
39
# File 'lib/facon/proxy.rb', line 33

def add_negative_expectation(expected_from, method, &block)
  $facon_mocks << (@target) unless $facon_mocks.nil?
  define_expected_method(method)

  @expectations << NegativeExpectation.new(@error_generator, @expectation_ordering, expected_from, method, (block_given? ? block : nil))
  @expectations.last
end

#add_stub(expected_from, method) ⇒ Object



16
17
18
19
20
21
22
23
# File 'lib/facon/proxy.rb', line 16

def add_stub(expected_from, method)
  $facon_mocks << (@target) unless $facon_mocks.nil?
  define_expected_method(method)

  # A stub is really an expectation that can be called any number of times.
  @stubs.unshift(Expectation.new(@error_generator, @expectation_ordering, expected_from, method, nil, :any))
  @stubs.first
end

#message_received(method, *args, &block) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
# File 'lib/facon/proxy.rb', line 41

def message_received(method, *args, &block)
  if expectation = find_matching_expectation(method, *args)
    expectation.invoke(args, block)
  elsif stub = find_matching_method_stub(method, *args)
    stub.invoke([], block)
  elsif expectation = find_almost_matching_expectation(method, *args)
    raise_unexpected_message_args_error(expectation, *args) unless has_negative_expectation?(method)
  else
    @target.send(:method_missing, method, *args, &block)
  end
end

#resetObject



59
60
61
62
# File 'lib/facon/proxy.rb', line 59

def reset
  @expectations.clear
  @stubs.clear
end

#verifyObject



53
54
55
56
57
# File 'lib/facon/proxy.rb', line 53

def verify
  @expectations.each { |expectation| expectation.met? }
ensure
  reset
end