Skip to content

Instantly share code, notes, and snippets.

@simonbaird
Created March 13, 2015 01:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simonbaird/416f15d8ddf697ad6132 to your computer and use it in GitHub Desktop.
Save simonbaird/416f15d8ddf697ad6132 to your computer and use it in GitHub Desktop.
Stubbing a constant in ruby
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
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