跳到內容 跳到搜尋
方法
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

注意:建立 const 的 stub 會跨所有執行緒建立 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