在RSpec中重新分配实例变量



我有一系列测试需要按顺序运行,因此,我需要在所有规范中保持公共状态。根据我对上下文挂钩之前的阅读,我假设我能够从示例内部重新分配实例变量。

我似乎不能重新分配它们,但我可以修改它们。下面是一个工作示例:

require "rspec/expectations"
RSpec.describe "Array", order: :defined do
before(:context) do
@array = []
end
describe "initialized in before(:context)" do
it "is empty" do
expect(@array.size).to eq(0) # Passes
end
it "accepts objects" do
@array << Object.new # Passes
end
it "shares state across examples" do
expect(@array.size).to eq(1) # Passes
end
it "can reassign the array" do
@array = [] # Passes, but this seems to only be assigned locally?
end
it "still shares state across examples" do
expect(@array.count).to eq(0) # => FAILURE: @array.count == 1
end
end
end

如何在上面的例子中重新分配@array

因此,需要明确的是,我已经有了一个不涉及重新分配实例变量的变通方法。这是张贴在下面我不想找变通办法。我想知道我是否可以重新分配实例变量,或者为什么不能

# This passes with no issues
RSpec.describe "Array in a Struct", order: :defined do
before(:context) do
@o = OpenStruct.new
@o.array = []
end
describe "initialized in before(:context)" do
it "is empty" do
expect(@o.array.size).to eq(0) # Passes
end
it "accepts objects" do
@o.array << Object.new # Passes
end
it "shares state across examples" do
expect(@o.array.size).to eq(1) # Passes
end
it "can reassign the array" do
@o.array = [] # Passes
end
it "still shares state across examples" do
expect(@o.array.count).to eq(0) # Passes
end
end
end

我不希望像这样简单的实例变量赋值能起作用,但您可以尝试使用Thread.current作为存储空间。

最新更新