跳到內容 跳到搜尋

提供一些輔助工具來處理測試日誌訂閱者,方法是設定通知。例如 Active Record 訂閱者測試

class SyncLogSubscriberTest < ActiveSupport::TestCase
  include ActiveSupport::LogSubscriber::TestHelper

  setup do
    ActiveRecord::LogSubscriber.attach_to(:active_record)
  end

  def test_basic_query_logging
    Developer.all.to_a
    wait
    assert_equal 1, @logger.logged(:debug).size
    assert_match(/Developer Load/, @logger.logged(:debug).last)
    assert_match(/SELECT \* FROM "developers"/, @logger.logged(:debug).last)
  end
end

您只需要確保您的日誌訂閱者已新增至 Rails::Subscriber,如上述程式碼的第二行。測試輔助工具負責設定佇列和訂閱,以及關閉日誌中的色彩。

訊息會出現在 @logger 實例中,這是一個功能有限的記錄器(它實際上不會將任何內容傳送至您的輸出),您可以執行 @logger.logged(level) 來收集它們,其中 level 是記錄中使用的層級,例如資訊、偵錯、警告等。

命名空間
方法
S
W

實例公開方法

set_logger(logger)

如果您在日誌訂閱者中使用其他記錄器,請覆寫。

def logger
  ActiveRecord::Base.logger = @logger
end
# File activesupport/lib/active_support/log_subscriber/test_helper.rb, line 101
def set_logger(logger)
  ActiveSupport::LogSubscriber.logger = logger
end

wait()

等待通知發布。

# File activesupport/lib/active_support/log_subscriber/test_helper.rb, line 92
def wait
  @notifier.wait
end