Skip to content

Commit bdbe61c

Browse files
authored
Capture errors outside examples (#16)
In our efforts to improve RSpec output, we've lacked a way to easily parse errors when they occur outside of examples. Adding an easier way to access that information feels aligned with the goals of this gem. This commit adds an "errors" key that populates with information (exception class, exception message, path, and line number) about errors that occur outside of examples.
1 parent 8802054 commit bdbe61c

2 files changed

Lines changed: 37 additions & 1 deletion

File tree

lib/rspec/enriched_json/formatters/enriched_json_formatter.rb

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,20 @@ module RSpec
77
module EnrichedJson
88
module Formatters
99
class EnrichedJsonFormatter < RSpec::Core::Formatters::JsonFormatter
10+
ANSI_COLOR_REGEX = /\e\[[0-9;]*[mGKHF]/
11+
EXCEPTION_DETECTOR_REGEX = /(Exception|Error|undefined method|uninitialized constant)/
12+
PATH_AND_LINE_NUMBER_REGEX = /#?(?<path>.+?):(?<line_number>\d+)/
13+
EXCEPTION_CLASS_AND_MESSAGE_REGEX = /^(?<exception_class>[A-Z]\w*Error|Exception):$\n(?<exception_message>(?<extra>^\s\s.*\n?)+)/
14+
1015
RSpec::Core::Formatters.register self, :message, :dump_summary, :dump_profile, :stop, :seed, :close
1116

17+
def initialize(output)
18+
super
19+
@output_hash = {
20+
errors: []
21+
}
22+
end
23+
1224
def stop(group_notification)
1325
@output_hash[:examples] = group_notification.notifications.map do |notification|
1426
format_example(notification.example).tap do |hash|
@@ -36,6 +48,30 @@ def stop(group_notification)
3648
end
3749
end
3850

51+
def message(notification)
52+
super
53+
54+
if notification.message.match?(EXCEPTION_DETECTOR_REGEX)
55+
clean_message = notification.message.gsub(ANSI_COLOR_REGEX, "")
56+
57+
error_info = {
58+
message: clean_message
59+
}
60+
61+
if (match = clean_message.match(PATH_AND_LINE_NUMBER_REGEX))
62+
error_info[:path] = match.named_captures["path"]
63+
error_info[:line_number] = match.named_captures["line_number"]
64+
end
65+
66+
if (match = clean_message.match(EXCEPTION_CLASS_AND_MESSAGE_REGEX))
67+
error_info[:exception_class] = match.named_captures["exception_class"]
68+
error_info[:exception_message] = match.named_captures["exception_message"]
69+
end
70+
71+
@output_hash[:errors] << error_info
72+
end
73+
end
74+
3975
private
4076

4177
def add_metadata(hash, example)

lib/rspec/enriched_json/version.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,6 @@
22

33
module RSpec
44
module EnrichedJson
5-
VERSION = "0.8.0"
5+
VERSION = "0.8.1"
66
end
77
end

0 commit comments

Comments
 (0)