Use `safe_constantize`.

Fixes https://github.com/rails/rails/issues/9933.
This commit is contained in:
Guo Xiang Tan 2014-08-10 14:56:03 +08:00
parent fcbdac7e82
commit 6e0f273dfd
4 changed files with 41 additions and 5 deletions

View File

@ -36,12 +36,8 @@ module ActiveSupport
while names.size > 0 do
names.last.sub!(/Test$/, "")
begin
constant = names.join("::").constantize
constant = names.join("::").safe_constantize
break(constant) if yield(constant)
rescue NoMethodError # subclass of NameError
raise
rescue NameError
# Constant wasn't found, move on
ensure
names.pop
end

View File

@ -1,3 +1,5 @@
require 'dependencies_test_helpers'
module Ace
module Base
class Case
@ -23,6 +25,8 @@ class Object
end
module ConstantizeTestCases
include DependenciesTestHelpers
def run_constantize_tests_on
assert_equal Ace::Base::Case, yield("Ace::Base::Case")
assert_equal Ace::Base::Case, yield("::Ace::Base::Case")
@ -56,6 +60,19 @@ module ConstantizeTestCases
assert_raises(NameError) { yield("Ace::Gas::ConstantizeTestCases") }
assert_raises(NameError) { yield("") }
assert_raises(NameError) { yield("::") }
assert_raises(NameError) { yield("Ace::gas") }
assert_raises(NameError) do
with_autoloading_fixtures do
yield("RaisesNameError")
end
end
assert_raises(NoMethodError) do
with_autoloading_fixtures do
yield("RaisesNoMethodError")
end
end
end
def run_safe_constantize_tests_on
@ -82,5 +99,18 @@ module ConstantizeTestCases
assert_nil yield("Ace::Gas::Base")
assert_nil yield("Ace::Gas::ConstantizeTestCases")
assert_nil yield("#<Class:0x7b8b718b>::Nested_1")
assert_nil yield("Ace::gas")
assert_raises(NameError) do
with_autoloading_fixtures do
yield("RaisesNameError")
end
end
assert_raises(NoMethodError) do
with_autoloading_fixtures do
yield("RaisesNoMethodError")
end
end
end
end

View File

@ -888,6 +888,8 @@ class DependenciesTest < ActiveSupport::TestCase
assert_raise(NameError) { assert_equal 123, ::RaisesNameError::FooBarBaz }
end
end
ensure
remove_constants(:RaisesNameError)
end
def test_autoload_doesnt_shadow_name_error

View File

@ -65,4 +65,12 @@ class ConstantLookupTest < ActiveSupport::TestCase
}
}
end
def test_does_not_swallow_exception_on_no_name_error_within_constant
assert_raises(NameError) do
with_autoloading_fixtures do
self.class.determine_constant_from_test_name('RaisesNameError')
end
end
end
end