跳至内容 跳至搜索
方法
S

实例公共方法

stub_const(mod, constant, new_value, exists: true)

在块的持续时间内更改常量的值。示例

# World::List::Import::LARGE_IMPORT_THRESHOLD = 5000
stub_const(World::List::Import, :LARGE_IMPORT_THRESHOLD, 1) do
  assert_equal 1, World::List::Import::LARGE_IMPORT_THRESHOLD
end

assert_equal 5000, World::List::Import::LARGE_IMPORT_THRESHOLD

使用此方法而不是强制执行 World::List::Import::LARGE_IMPORT_THRESHOLD = 5000 可以防止发出警告,并确保在测试完成后返回旧值。

如果常量尚不存在,但您需要在块的持续时间内设置它,可以通过传递 `exists: false` 来实现。

stub_const(object, :SOME_CONST, 1, exists: false) do
  assert_equal 1, SOME_CONST
end

注意:Stubbing 一个常量会跨所有线程进行 stub。因此,如果您有并发线程(例如并行运行的独立测试套件)都依赖于相同的常量,则可能会出现不同的 stub 互相干扰的情况。

# File activesupport/lib/active_support/testing/constant_stubbing.rb, line 28
def stub_const(mod, constant, new_value, exists: true)
  if exists
    begin
      old_value = mod.const_get(constant, false)
      mod.send(:remove_const, constant)
      mod.const_set(constant, new_value)
      yield
    ensure
      mod.send(:remove_const, constant)
      mod.const_set(constant, old_value)
    end
  else
    if mod.const_defined?(constant)
      raise NameError, "already defined constant #{constant} in #{mod.name}"
    end

    begin
      mod.const_set(constant, new_value)
      yield
    ensure
      mod.send(:remove_const, constant)
    end
  end
end