Skip to content

Commit 92e088a

Browse files
committed
stub_const polishing
1 parent 6f6a04f commit 92e088a

File tree

2 files changed

+20
-7
lines changed

2 files changed

+20
-7
lines changed

activesupport/lib/active_support/testing/constant_stubbing.rb

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,22 +10,22 @@ module ConstantStubbing
1010
# assert_equal 1, World::List::Import::LARGE_IMPORT_THRESHOLD
1111
# end
1212
#
13-
# assert_equal 5000, World::List::Import::LARGE_IMPORT_THRESHOLD = 5000
13+
# assert_equal 5000, World::List::Import::LARGE_IMPORT_THRESHOLD
1414
#
1515
# Using this method rather than forcing <tt>World::List::Import::LARGE_IMPORT_THRESHOLD = 5000</tt> prevents
1616
# warnings from being thrown, and ensures that the old value is returned after the test has completed.
1717
#
1818
# Note: Stubbing a const will stub it across all threads. So if you have concurrent threads
1919
# (like separate test suites running in parallel) that all depend on the same constant, it's possible
2020
# divergent stubbing will trample on each other.
21-
def stub_const(klass, constant, new_value)
22-
old_value = klass.const_get(constant)
23-
klass.send(:remove_const, constant)
24-
klass.const_set(constant, new_value)
21+
def stub_const(mod, constant, new_value)
22+
old_value = mod.const_get(constant, false)
23+
mod.send(:remove_const, constant)
24+
mod.const_set(constant, new_value)
2525
yield
2626
ensure
27-
klass.send(:remove_const, constant)
28-
klass.const_set(constant, old_value)
27+
mod.send(:remove_const, constant)
28+
mod.const_set(constant, old_value)
2929
end
3030
end
3131
end

activesupport/test/test_case_test.rb

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -557,6 +557,9 @@ class ConstStubbable
557557
CONSTANT = 1
558558
end
559559

560+
class SubclassOfConstStubbable < ConstStubbable
561+
end
562+
560563
class TestConstStubbing < ActiveSupport::TestCase
561564
test "stubbing a constant temporarily replaces it with a new value" do
562565
stub_const(ConstStubbable, :CONSTANT, 2) do
@@ -576,4 +579,14 @@ class TestConstStubbing < ActiveSupport::TestCase
576579

577580
assert_equal 1, ConstStubbable::CONSTANT
578581
end
582+
583+
test "trying to stub a constant that does not exist in the receiver raises NameError" do
584+
assert_raises(NameError) do
585+
stub_const(ConstStubbable, :NOT_A_CONSTANT, 1) { }
586+
end
587+
588+
assert_raises(NameError) do
589+
stub_const(SubclassOfConstStubbable, :CONSTANT, 1) { }
590+
end
591+
end
579592
end

0 commit comments

Comments
 (0)