Skip to content

Instantly share code, notes, and snippets.

@sephraim
Last active February 28, 2023 05:56
Show Gist options
  • Save sephraim/6d2fd6654f9b86316b46b5ddffef2cec to your computer and use it in GitHub Desktop.
Save sephraim/6d2fd6654f9b86316b46b5ddffef2cec to your computer and use it in GitHub Desktop.
[Stub class constants] Stub class constants in RSpec tests
# Stubbing a single class constant is a little finicky and can remove all constants of a class if not done right
MyClass::MY_CONSTANT_1 #=> 'foo'
MyClass::MY_CONSTANT_2 #=> 'bar'
# METHOD 1 (PREFERRED)
before(:example) do
stub_const('MyClass', MyClass)
stub_const('MyClass::MY_CONSTANT_1', 'baz')
end
MyClass::MY_CONSTANT_1 #=> 'baz'
MyClass::MY_CONSTANT_2 #=> 'bar'
# METHOD 2 (NOT AS GOOD)
around(:example) do |example|
# Stub constant
original = MyClass.send(:remove_const, :MY_CONSTANT_1)
MyClass.const_set(:MY_CONSTANT_1, 'baz')
example.run
# Put original value back again
MyClass.send(:remove_const, :MY_CONSTANT_1)
MyClass.const_set(:MY_CONSTANT_1, original)
end
MyClass::MY_CONSTANT_1 #=> 'baz'
MyClass::MY_CONSTANT_2 #=> 'bar'
# WHAT *NOT* TO DO:
before(:example) do
stub_const('MyClass::MY_CONSTANT_1', 'baz')
end
MyClass::MY_CONSTANT_1 #=> 'baz'
MyClass::MY_CONSTANT_2 #=> NameError Exception: uninitialized constant MyClass::MY_CONSTANT_2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment