rspec上下文的范围常量

时间:2011-03-08 08:31:30

标签: rspec constants rspec2

我经常想做

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​​不会将常量范围限制为闭包,因此它们会泄漏出来。有没有人有一个技巧来声明作用于上下文的常量?

3 个答案:

答案 0 :(得分:22)

更改常量的声明:
来自SOME_CONSTANT = "value"
self::SOME_CONSTANT = "value"

RSpec为它遇到的每组规范(示例中的上下文)创建一个匿名类。在匿名类中声明不带self::的常量使其在全局范围内可用,并且对所有规范都可见。将常量声明更改为self::可确保它仅在匿名类中可见。

答案 1 :(得分:20)

现在使用了较长时间的rspec,我认为更惯用的方法是使用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

答案 2 :(得分:1)

正确的做法是使用 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