方法
实例公共方法
stub_const(mod, constant, new_value) 链接
在块持续期间更改常量值。示例
# 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
可以防止发出警告,并确保在测试完成后返回旧值。
注意:存根常量将在所有线程中存根它。因此,如果你有并发线程(如并行运行的单独测试套件),它们都依赖于同一个常量,那么不同的存根可能会互相践踏。
来源: 显示 | 在 GitHub 上
# File activesupport/lib/active_support/testing/constant_stubbing.rb, line 21 def stub_const(mod, constant, new_value) 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