Last active
February 28, 2023 05:56
-
-
Save sephraim/6d2fd6654f9b86316b46b5ddffef2cec to your computer and use it in GitHub Desktop.
[Stub class constants] Stub class constants in RSpec tests
This file contains hidden or 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
# 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