Module: RSpec::Mocks::TestDouble

Included in:
Mock
Defined in:
lib/rspec/mocks/test_double.rb

Overview

Implements the methods needed for a pure test double. RSpec::Mocks::Mock includes this module, and it is provided for cases where you want a pure test double without subclassing RSpec::Mocks::Mock.

Class Method Summary (collapse)

Instance Method Summary (collapse)

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

- (Object) method_missing(message, *args) (private)

86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/rspec/mocks/test_double.rb', line 86
def method_missing(message, *args, &block)
  if __mock_proxy.null_object?
    case message
    when :to_int        then return 0
    when :to_a, :to_ary then return nil
    end
  end
  __mock_proxy.record_message_received(message, *args, &block)
  begin
    __mock_proxy.null_object? ? self : super
  rescue NameError
    # Required wrapping doubles in an Array on Ruby 1.9.2
    raise NoMethodError if [:to_a, :to_ary].include? message
    __mock_proxy.raise_unexpected_message_error(message, *args)
  end
end

Class Method Details

+ (Object) extend_onto(object, name = nil, stubs_and_options = {})

Extends the TestDouble module onto the given object and initializes it as a test double.

Examples:

module = Module.new
RSpec::Mocks::TestDouble.extend_onto(module, "MyMixin", :foo => "bar")
module.foo  #=> "bar"
15
16
17
18
# File 'lib/rspec/mocks/test_double.rb', line 15
def self.extend_onto(object, name=nil, stubs_and_options={})
  object.extend self
  object.send(:__initialize_as_test_double, name, stubs_and_options)
end

Instance Method Details

- (Object) ==(other)

This allows for comparing the mock to other objects that proxy such as ActiveRecords belongs_to proxy objects. By making the other object run the comparison, we're sure the call gets delegated to the proxy target.

43
44
45
# File 'lib/rspec/mocks/test_double.rb', line 43
def ==(other)
  other == __mock_proxy
end

- (Object) as_null_object

Tells the object to respond to all messages. If specific stub values are declared, they'll work as expected. If not, the receiver is returned.

29
30
31
32
# File 'lib/rspec/mocks/test_double.rb', line 29
def as_null_object
  @__null_object = true
  __mock_proxy.as_null_object
end

- (TestDouble) initialize(name = nil, stubs_and_options = {})

Creates a new test double with a name (that will be used in error messages only)

22
23
24
# File 'lib/rspec/mocks/test_double.rb', line 22
def initialize(name=nil, stubs_and_options={})
  __initialize_as_test_double(name, stubs_and_options)
end

- (Boolean) null_object?

Returns true if this object has received as_null_object

Returns:

  • (Boolean)
35
36
37
# File 'lib/rspec/mocks/test_double.rb', line 35
def null_object?
  @__null_object
end