-
-
Notifications
You must be signed in to change notification settings - Fork 119
/
test_exceptions.rb
81 lines (71 loc) · 2.82 KB
/
test_exceptions.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# frozen_string_literal: true
require "test_helper"
class TestExceptions < LoaderTest
# We cannot test error.message only because after
#
# https://github.com/ruby/ruby/commit/e94604966572bb43fc887856d54aa54b8e9f7719
#
# error.message includes the line of code that raised.
def assert_error_message(message, error)
assert_equal message, error.message.lines.first.chomp
end
test "raises NameError if the expected constant is not defined" do
files = [["typo.rb", "TyPo = 1"]]
with_setup(files) do
typo_rb = File.expand_path("typo.rb")
error = assert_raises(Zeitwerk::NameError) { Typo }
assert_error_message "expected file #{typo_rb} to define constant Typo, but didn't", error
assert_equal :Typo, error.name
end
end
test "eager loading raises NameError if files do not define the expected constants" do
on_teardown do
remove_const :X # should be unnecessary, but $LOADED_FEATURES.reject! redefines it
remove_const :Y
end
files = [["x.rb", "Y = 1"]]
with_setup(files) do
x_rb = File.expand_path("x.rb")
error = assert_raises(Zeitwerk::NameError) { loader.eager_load }
assert_error_message "expected file #{x_rb} to define constant X, but didn't", error
assert_equal :X, error.name
end
end
test "eager loading raises NameError if a namespace has not been loaded yet" do
on_teardown do
remove_const :CLI
delete_loaded_feature 'cli/x.rb'
end
files = [["cli/x.rb", "module CLI; X = 1; end"]]
with_setup(files) do
cli_x_rb = File.expand_path("cli/x.rb")
error = assert_raises(Zeitwerk::NameError) { loader.eager_load }
assert_error_message "expected file #{cli_x_rb} to define constant Cli::X, but didn't", error
assert_equal :X, error.name
end
end
test "raises if the file does" do
files = [["raises.rb", "Raises = 1; raise 'foo'"]]
with_setup(files, rm: false) do
assert_raises(RuntimeError, "foo") { Raises }
end
end
test "raises Zeitwerk::NameError if the inflector returns an invalid constant name for a file" do
files = [["foo-bar.rb", "FooBar = 1"]]
error = assert_raises Zeitwerk::NameError do
with_setup(files) {}
end
assert_equal :"Foo-bar", error.name
assert_includes error.message, "wrong constant name Foo-bar"
assert_includes error.message, "Tell Zeitwerk to ignore this particular file."
end
test "raises Zeitwerk::NameError if the inflector returns an invalid constant name for a directory" do
files = [["foo-bar/baz.rb", "FooBar::Baz = 1"]]
error = assert_raises Zeitwerk::NameError do
with_setup(files) {}
end
assert_equal :"Foo-bar", error.name
assert_includes error.message, "wrong constant name Foo-bar"
assert_includes error.message, "Tell Zeitwerk to ignore this particular directory."
end
end