Created
March 13, 2015 01:26
-
-
Save simonbaird/416f15d8ddf697ad6132 to your computer and use it in GitHub Desktop.
Stubbing a constant in ruby
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
module WithStubbedConst | |
def with_stubbed_const(consts, scope=self.class) | |
stash = {} | |
consts.each_pair do |key, val| | |
stash[key] = scope.send(:remove_const, key) | |
scope.send(:const_set, key, val) | |
end | |
begin | |
yield | |
ensure | |
consts.each_pair do |key, val| | |
scope.send(:remove_const, key) | |
scope.send(:const_set, key, stash[key]) | |
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
require 'test/unit' | |
require 'test_helper/with_stubbed_const' | |
class TestWithStubbedConst < Test::Unit::TestCase | |
include WithStubbedConst | |
module Bar | |
BAZ = 10 | |
end | |
FOO = "foo" | |
def test_default_scope | |
assert_equal "foo", FOO | |
with_stubbed_const(:FOO => "changed!") { assert_equal "changed!", FOO } | |
assert_equal "foo", FOO | |
end | |
def test_specified_scope | |
assert_equal 10, Bar::BAZ | |
with_stubbed_const({:BAZ => 20}, Bar) { assert_equal 20, Bar::BAZ } | |
assert_equal 10, Bar::BAZ | |
end | |
def test_block_raises | |
assert_equal "foo", FOO | |
with_stubbed_const(:FOO => 99) { assert_equal 99, FOO; raise "boom" } rescue nil | |
assert_equal "foo", FOO | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment