Scope constants to an rspec context

opsb picture opsb · Mar 8, 2011 · Viewed 9.4k times · Source

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?

Answer

naren picture naren · May 17, 2011

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.