I often want to do
context "empty stack" do SOME_CONSTANT = "value" it "should be empty" do # use SOME_CONSTANT end end context "populated stack" do SOME_CONSTANT = "a different value" it "should have some items" do # use SOME_CONSTANT end end
ruby doesn't scope constants to closures so they leak out. Does anyone have a trick for declaring constants that are scoped to a context?
Change the declaration of the constant:
from SOME_CONSTANT = "value"
to self::SOME_CONSTANT = "value"
RSpec creates an anonymous class for each set of specs (context in your example) that it comes across. Declaring a constant without self::
in an anonymous class makes it available in global scope, and is visible to all the specs. Changing the constant declaration to self::
ensures that it is visible only within the anonymous class.
Having used rspec for longer now I think the more idiomatic approach is to use let.
context "empty stack" do let(:some_constant){ "value" } it "should be empty" do puts some_constant end end context "populated stack" do let(:some_constant){ "a different value" } it "should have some items" do puts some_constant end end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With