开发者

Scope constants to an rspec context

开发者 https://www.devze.com 2023-02-15 06:28 出处:网络
I often want to do context \"empty stack\" do SOME_CONSTANT = \"value\" it \"should be empty\" do # use SOME_CONSTANT

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"
开发者_Go百科  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


The correct way to do it is to use stub_const

RSpec.describe "stubbing FOO" do
  it "can stub undefined constant FOO" do
    stub_const("FOO", 5)
    expect(FOO).to eq(5)
  end

  it "undefines the constant when the example completes" do
    expect { FOO }.to raise_error(NameError)
  end
end

https://relishapp.com/rspec/rspec-mocks/v/3-9/docs/mutating-constants/stub-undefined-constant

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号