Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* Add TestCase#stub_const * Note the concurrency issue * Changelog entry
- Loading branch information
Showing
4 changed files
with
62 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
30 changes: 30 additions & 0 deletions
30
activesupport/lib/active_support/testing/constant_stubbing.rb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
module ActiveSupport | ||
module Testing | ||
module ConstantStubbing | ||
# Changes the value of a constant for the duration of a block. Example: | ||
# | ||
# # World::List::Import::LARGE_IMPORT_THRESHOLD = 5000 | ||
# stub_const(World::List::Import, :LARGE_IMPORT_THRESHOLD, 1) do | ||
# assert_equal 1, World::List::Import::LARGE_IMPORT_THRESHOLD | ||
# end | ||
# | ||
# assert_equal 5000, World::List::Import::LARGE_IMPORT_THRESHOLD = 5000 | ||
# | ||
# Using this method rather than forcing `World::List::Import::LARGE_IMPORT_THRESHOLD = 5000` prevents | ||
# warnings from being thrown, and ensures that the old value is returned after the test has completed. | ||
# | ||
# Note: Stubbing a const will stub it across all threads. So if you have concurrent threads | ||
# (like separate test suites running in parallel) that all depend on the same constant, it's possible | ||
# divergent stubbing will trample on each other. | ||
def stub_const(klass, constant, new_value) | ||
old_value = klass.const_get(constant) | ||
klass.send(:remove_const, constant) | ||
klass.const_set(constant, new_value) | ||
yield | ||
ensure | ||
klass.send(:remove_const, constant) | ||
klass.const_set(constant, old_value) | ||
end | ||
end | ||
end | ||
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters