略過內容 略過搜尋

透過設定通知來提供一些輔助程式以處理測試日誌訂閱者。以 ActiveRecord 訂閱者測試為例

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