模块: RSpec::Mocks::TestDouble

包含在
Double
定义在
lib/rspec/mocks/test_double.rb

概述

实现纯测试替身所需的方法。RSpec::Mocks::Double 包含此模块,并提供用于在不子类化 RSpec::Mocks::Double 的情况下需要纯测试替身的情况。

实例方法摘要 折叠

动态方法处理

此类通过以下方式处理动态方法method_missing方法

#method_missing(message, *args, &block) ⇒Object (私有)

引发

  • (NoMethodError)
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/rspec/mocks/test_double.rb', line 74
def method_missing(message, *args, &block)
  proxy = __mock_proxy
  proxy.record_message_received(message, *args, &block)
  if proxy.null_object?
    case message
    when :to_int        then return 0
    when :to_a, :to_ary then return nil
    when :to_str        then return to_s
    else return self
    end
  end
  # Defined private and protected methods will still trigger `method_missing`
  # when called publicly. We want ruby's method visibility error to get raised,
  # so we simply delegate to `super` in that case.
  # ...well, we would delegate to `super`, but there's a JRuby
  # bug, so we raise our own visibility error instead:
  # https://github.com/jruby/jruby/issues/1398
  visibility = proxy.visibility_for(message)
  if visibility == :private || visibility == :protected
    ErrorGenerator.new(self).raise_non_public_error(
      message, visibility
    )
  end
  # Required wrapping doubles in an Array on Ruby 1.9.2
  raise NoMethodError if [:to_a, :to_ary].include? message
  proxy.raise_unexpected_message_error(message, args)
end

实例方法详细信息

#==(other) ⇒Object

这允许将模拟与其他代理对象进行比较,例如 ActiveRecord 的 belongs_to 代理对象。通过让其他对象运行比较,我们可以确保调用被委托给代理目标。

36
37
38
# File 'lib/rspec/mocks/test_double.rb', line 36
def ==(other)
  other == __mock_proxy
end

#as_null_objectObject

告诉对象对所有消息进行响应。如果声明了特定的存根值,它们将按预期工作。如果没有,则返回接收者。

23
24
25
# File 'lib/rspec/mocks/test_double.rb', line 23
def as_null_object
  __mock_proxy.as_null_object
end

#freezeObject

覆盖默认的冻结实现,以防止冻结测试替身。

67
68
69
70
# File 'lib/rspec/mocks/test_double.rb', line 67
def freeze
  RSpec.warn_with("WARNING: you attempted to freeze a test double. This is explicitly a no-op as freezing doubles can lead to undesired behaviour when resetting tests.")
  self
end

#initialize(name = nil, stubs = {}) ⇒Object

使用 name(仅用于错误消息)创建一个新的测试替身

9
10
11
12
13
14
15
16
17
18
# File 'lib/rspec/mocks/test_double.rb', line 9
def initialize(name=nil, stubs={})
  @__expired = false
  if Hash === name && stubs.empty?
    stubs = name
    @name = nil
  else
    @name = name
  end
  assign_stubs(stubs)
end

#null_object?布尔值

如果此对象已收到 as_null_object,则返回 true

返回

  • (布尔值)
28
29
30
# File 'lib/rspec/mocks/test_double.rb', line 28
def null_object?
  __mock_proxy.null_object?
end