方法
實體公開方法
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