Skip to content

Commit 7bc1666

Browse files
committed
Merge pull request #972 from bf4/capture_app_warnings
Capture app warnings on test run
2 parents 438d8f4 + e7174a7 commit 7bc1666

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed

test/capture_warnings.rb

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
# https://raw.githubusercontent.com/metric_fu/metric_fu/master/spec/capture_warnings.rb
2+
require "tempfile"
3+
require "fileutils"
4+
5+
class CaptureWarnings
6+
def initialize(fail_on_warnings = true)
7+
@fail_on_warnings = fail_on_warnings
8+
@stderr_file = Tempfile.new("app.stderr")
9+
@app_root ||= Dir.pwd
10+
@output_dir = File.join(app_root, "tmp")
11+
FileUtils.mkdir_p(output_dir)
12+
@bundle_dir = File.join(app_root, "bundle")
13+
end
14+
15+
def before_tests
16+
$stderr.reopen(stderr_file.path)
17+
$VERBOSE = true
18+
at_exit { $stderr.reopen(STDERR) }
19+
end
20+
21+
def after_tests
22+
stderr_file.rewind
23+
lines = stderr_file.read.split("\n").uniq
24+
stderr_file.close!
25+
26+
$stderr.reopen(STDERR)
27+
28+
app_warnings, other_warnings = lines.partition { |line|
29+
line.include?(app_root) && !line.include?(bundle_dir)
30+
}
31+
32+
if app_warnings.any?
33+
puts <<-WARNINGS
34+
#{'-' * 30} app warnings: #{'-' * 30}
35+
36+
#{app_warnings.join("\n")}
37+
38+
#{'-' * 75}
39+
WARNINGS
40+
end
41+
42+
if other_warnings.any?
43+
File.write(File.join(output_dir, "warnings.txt"), other_warnings.join("\n") << "\n")
44+
puts
45+
puts "Non-app warnings written to tmp/warnings.txt"
46+
puts
47+
end
48+
49+
# fail the build...
50+
if fail_on_warnings && app_warnings.any?
51+
abort "Failing build due to app warnings: #{app_warnings.inspect}"
52+
end
53+
end
54+
55+
private
56+
attr_reader :stderr_file, :app_root, :output_dir, :bundle_dir, :fail_on_warnings
57+
end

test/test_helper.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,12 @@
1111
# Ensure backward compatibility with Minitest 4
1212
Minitest::Test = MiniTest::Unit::TestCase unless defined?(Minitest::Test)
1313

14+
require "capture_warnings"
15+
@capture_warnings = CaptureWarnings.new(fail_build = false)
16+
@capture_warnings.before_tests
17+
at_exit do
18+
@capture_warnings.after_tests
19+
end
1420
require 'active_model_serializers'
1521

1622
class Foo < Rails::Application

0 commit comments

Comments
 (0)