Class: RailsSemanticLogging::RSpec::LogSemanticMatcher

Inherits:
Object
  • Object
show all
Defined in:
lib/rails_semantic_logging/rspec/matchers.rb

Overview

RSpec matcher for asserting log output from a block.

Usage:

expect { logger.info("hello") }.to log_semantic(level: :info, message: /hello/)
expect { logger.warn("oops", payload: { key: "val" }) }.to log_semantic(payload: { key: "val" })

Instance Method Summary collapse

Constructor Details

#initialize(expected) ⇒ LogSemanticMatcher

Returns a new instance of LogSemanticMatcher.



29
30
31
32
33
34
35
# File 'lib/rails_semantic_logging/rspec/matchers.rb', line 29

def initialize(expected)
  @expected_level = expected[:level]
  @expected_message = expected[:message]
  @expected_named_tags = expected[:named_tags]
  @expected_payload = expected[:payload]
  @captured_logs = []
end

Instance Method Details

#failure_messageObject



56
57
58
# File 'lib/rails_semantic_logging/rspec/matchers.rb', line 56

def failure_message
  "expected block to log a message matching #{expected_description}, but captured logs were:\n#{format_logs}"
end

#failure_message_when_negatedObject



60
61
62
# File 'lib/rails_semantic_logging/rspec/matchers.rb', line 60

def failure_message_when_negated
  "expected block not to log a message matching #{expected_description}, but it did"
end

#matches?(block) ⇒ Boolean

Returns:

  • (Boolean)


37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/rails_semantic_logging/rspec/matchers.rb', line 37

def matches?(block)
  appender = InMemoryAppender.new
  SemanticLogger.add_appender(appender: appender)
  # Temporarily lower log level to capture all messages
  previous_level = SemanticLogger.default_level
  SemanticLogger.default_level = :trace
  block.call
  SemanticLogger.flush
  SemanticLogger.default_level = previous_level
  SemanticLogger.remove_appender(appender)

  @captured_logs = appender.logs
  @captured_logs.any? { |log| matches_log?(log) }
end

#supports_block_expectations?Boolean

Returns:

  • (Boolean)


52
53
54
# File 'lib/rails_semantic_logging/rspec/matchers.rb', line 52

def supports_block_expectations?
  true
end