Class: Spec::Api::Mock

Inherits:
Object show all
Defined in:
lib/spec/api/mocks/mock.rb

Instance Method Summary collapse

Constructor Details

#initialize(name, options = {}) ⇒ Mock

Creates a new mock with a name (that will be used in error messages only) Options:

  • :null_object - if true, the mock object acts as a forgiving null object allowing any message to be sent to it.



12
13
14
15
16
17
# File 'lib/spec/api/mocks/mock.rb', line 12

def initialize(name, options={})
  @name = name
  @options = DEFAULT_OPTIONS.dup.merge(options)
  @expectations = []
  @expectation_ordering = OrderGroup.new
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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



35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/spec/api/mocks/mock.rb', line 35

def method_missing(sym, *args, &block)
  if expectation = find_matching_expectation(sym, *args)
    expectation.invoke(args, block)
  else
    begin
      # act as null object if method is missing and we ignore them. return value too!
      @options[:null_object] ? self : super(sym, *args, &block)
    rescue NoMethodError
      arg_message = args.collect{|arg| "<#{arg}:#{arg.class.name}>"}.join(", ")
      Kernel::raise Spec::Api::MockExpectationError, "Mock '#{@name}' received unexpected message '#{sym}' with [#{arg_message}]"
    end
  end
end

Instance Method Details

#__verifyObject

:nodoc:



29
30
31
32
33
# File 'lib/spec/api/mocks/mock.rb', line 29

def __verify #:nodoc:
  @expectations.each do |expectation|
    expectation.verify_messages_received
  end
end

#should_not_receive(sym, &block) ⇒ Object



26
27
# File 'lib/spec/api/mocks/mock.rb', line 26

def should_not_receive(sym, &block)
end

#should_receive(sym, &block) ⇒ Object



19
20
21
22
23
24
# File 'lib/spec/api/mocks/mock.rb', line 19

def should_receive(sym, &block)
  expected_from = caller(1)[0]
  expectation = MessageExpectation.new(@name, @expectation_ordering, expected_from, sym, block_given? ? block : nil)
  @expectations << expectation
  expectation
end