Module: ActiveSupport::LogSubscriber::TestHelper

Defined in:
lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/activesupport-7.0.4/lib/active_support/log_subscriber/test_helper.rb

Overview

Provides some helpers to deal with testing log subscribers by setting up notifications. Take for instance Active Record subscriber tests:

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

All you need to do is to ensure that your log subscriber is added to Rails::Subscriber, as in the second line of the code above. The test helpers are responsible for setting up the queue and subscriptions, and turning colors in logs off.

The messages are available in the @logger instance, which is a logger with limited powers (it actually does not send anything to your output), and you can collect them doing @logger.logged(level), where level is the level used in logging, like info, debug, warn, and so on.

Defined Under Namespace

Classes: MockLogger

Instance Method Summary collapse

Instance Method Details

#set_logger(logger) ⇒ Object

Overwrite if you use another logger in your log subscriber.

def logger
  ActiveRecord::Base.logger = @logger
end


101
102
103
# File 'lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/activesupport-7.0.4/lib/active_support/log_subscriber/test_helper.rb', line 101

def set_logger(logger)
  ActiveSupport::LogSubscriber.logger = logger
end

#setupObject

:nodoc:



38
39
40
41
42
43
44
45
46
47
# File 'lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/activesupport-7.0.4/lib/active_support/log_subscriber/test_helper.rb', line 38

def setup # :nodoc:
  @logger   = MockLogger.new
  @notifier = ActiveSupport::Notifications::Fanout.new

  ActiveSupport::LogSubscriber.colorize_logging = false

  @old_notifier = ActiveSupport::Notifications.notifier
  set_logger(@logger)
  ActiveSupport::Notifications.notifier = @notifier
end

#teardownObject

:nodoc:



49
50
51
52
# File 'lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/activesupport-7.0.4/lib/active_support/log_subscriber/test_helper.rb', line 49

def teardown # :nodoc:
  set_logger(nil)
  ActiveSupport::Notifications.notifier = @old_notifier
end

#waitObject

Wait notifications to be published.



92
93
94
# File 'lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/activesupport-7.0.4/lib/active_support/log_subscriber/test_helper.rb', line 92

def wait
  @notifier.wait
end