Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope constants to an rspec context

Tags:

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?

like image 912
opsb Avatar asked Mar 08 '11 08:03

opsb


2 Answers

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.

like image 111
naren Avatar answered Sep 20 '22 13:09

naren


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 
like image 36
opsb Avatar answered Sep 16 '22 13:09

opsb