类: RSpec::Mocks::ConstantMutator

继承自
Object
  • Object
显示所有
扩展自
Support::RecursiveConstMethods
定义在
lib/rspec/mocks/mutate_const.rb

概述

提供了一种模拟常量的方法。

类方法摘要 折叠

类方法详情

.hide(constant_name) ⇒Object

注意

建议您在示例中使用 hide_const。 这是一个备用公共 API,提供用于在其他上下文中隐藏常量(例如,辅助类)。

隐藏常量。

参数

  • constant_name (String)

    常量的完全限定名称。 调用时的当前常量作用域不被考虑。

另见

131
132
133
134
# File 'lib/rspec/mocks/mutate_const.rb', line 131
def self.hide(constant_name)
  mutate(ConstantHider.new(constant_name, nil, {}))
  nil
end

.raise_on_invalid_constObject

此方法是私有 API 的一部分。 应尽可能避免使用此方法,因为它可能在将来被移除或更改。

在常量模拟内部使用,当像 "A::B::C" 这样的常量被模拟,而 A::B 不是一个模块时(因此,无法定义 "A::B::C",因为只有模块可以拥有嵌套常量)时,抛出一个有用的错误。

331
332
333
334
335
336
# File 'lib/rspec/mocks/mutate_const.rb', line 331
def self.raise_on_invalid_const
  lambda do |const_name, failed_name|
    raise "Cannot stub constant #{failed_name} on #{const_name} " \
          "since #{const_name} is not a module."
  end
end

.stub(constant_name, value, options = {}) ⇒Object

注意

建议您在示例中使用 stub_const。 这是一个备用公共 API,提供用于在其他上下文中模拟常量(例如,辅助类)。

模拟常量。

参数

  • constant_name (String)

    常量的完全限定名称。 调用时的当前常量作用域不被考虑。

  • value (Object)

    要使常量引用的值。 示例完成后,常量将恢复到其先前状态。

  • options (Hash) (默认为: {})

    模拟选项。

选项哈希 (options):

  • :transfer_nested_constants (Boolean, Array<Symbol>)

    确定将哪些嵌套常量(如果有)从常量的原始值转移到常量的新的值。 这只有在原始值和新值都是模块(或类)时才有效。

返回

  • (Object)

    常量的模拟值

另见

107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/rspec/mocks/mutate_const.rb', line 107
def self.stub(constant_name, value, options={})
  unless String === constant_name
    raise ArgumentError, "`stub_const` requires a String, but you provided a #{constant_name.class.name}"
  end
  mutator = if recursive_const_defined?(constant_name, &raise_on_invalid_const)
              DefinedConstantReplacer
            else
              UndefinedConstantSetter
            end
  mutate(mutator.new(constant_name, value, options[:transfer_nested_constants]))
  value
end