Blob of rspec/lib/spec/mocks/mock.rb (raw blob data)

1 module Spec
2 module Mocks
3 class Mock
4 include Methods
5
6 # Creates a new mock with a +name+ (that will be used in error messages
7 # only) == Options:
8 # * <tt>:null_object</tt> - if true, the mock object acts as a forgiving
9 # null object allowing any message to be sent to it.
10 def initialize(name, stubs_and_options={})
11 @name = name
12 @options = parse_options(stubs_and_options)
13 assign_stubs(stubs_and_options)
14 end
15
16 # This allows for comparing the mock to other objects that proxy such as
17 # ActiveRecords belongs_to proxy objects By making the other object run
18 # the comparison, we're sure the call gets delegated to the proxy target
19 # This is an unfortunate side effect from ActiveRecord, but this should
20 # be safe unless the RHS redefines == in a nonsensical manner
21 def ==(other)
22 other == __mock_proxy
23 end
24
25 def method_missing(sym, *args, &block)
26 __mock_proxy.instance_eval {@messages_received << [sym, args, block]}
27 begin
28 return self if __mock_proxy.null_object?
29 super(sym, *args, &block)
30 rescue NameError
31 __mock_proxy.raise_unexpected_message_error sym, *args
32 end
33 end
34
35 def inspect
36 "#<#{self.class}:#{sprintf '0x%x', self.object_id} @name=#{@name.inspect}>"
37 end
38
39 private
40
41 def parse_options(options)
42 options.has_key?(:null_object) ? {:null_object => options.delete(:null_object)} : {}
43 end
44
45 def assign_stubs(stubs)
46 stubs.each_pair do |message, response|
47 stub!(message).and_return(response)
48 end
49 end
50 end
51 end
52 end