在一个示例中分配的值不被携带到另一个示例中

时间:2018-05-31 05:45:58

标签: ruby rspec

在下文中,我在@variable中存储了example 1的值。但它在example 2中是空的。

class GeographicLocationTest < Minitest::Test
  describe "geographic location" do
    it "example 1" do
      @variable = "Sample variable"
    end
    it "example 2" do
      puts "string"
      puts @variable
    end
  end
end

任何人都会对我出错的地方提出建议。

2 个答案:

答案 0 :(得分:2)

实例变量不在it示例之间共享。您可以使用before块:

class GeographicLocationTest < Minitest::Test
  describe "geographic location" do
    before(:each) do
      @variable = "Sample variable"
    end

    it "example 1" do
      expect(@variable).to eq "Sample variable"
    end

    it "example 2" do
      expect(@variable).to eq "Sample variable"
    end
  end
end

before方法中初始化。它将适用于此处it中的每个describe

如果要在每个测试中为实例变量设置不同的值,则需要在那里重新分配。

答案 1 :(得分:1)

使用before hook:

class GeographicLocationTest < Minitest::Test
  describe "geographic location" do
    before do
      @variable = "Sample variable"
    end
    it "example 1" do
      # no need of the following line now
      @variable = "Sample variable"
    end
    it "example 2" do
      puts "string"
      puts @variable
    end
  end
end

有关documentation的更多信息。