rspec @variable返回零

问题描述 投票:0回答:3

我的@attributes变量存在问题。我希望可以保持我的代码干燥,但是目前,我必须重新设置变量并将其设置为“值”以使我的rspec测试工作。在没有重复值的情况下,有什么更好的方法可以做到这一点。

ref:Unexpected nil variable in RSpec

显示在描述中无法访问它,但需要另一种解决方案。何时“指定”是否合适?我没用过它。

describe "When one field is missing invalid " do 
    before(:each) do 
        @user = create(:user)
        @attributes = {"has_car"=>"true", "has_truck"=>"true", "has_boat"=>"true", "color"=>"blue value", "size"=>"large value"}
    end
  values = {"has_car"=>"true", "has_truck"=>"true", "has_boat"=>"true", "color"=>"blue value", "size"=>"large value"}
  values.keys.each do |f|
    p = values.except(f) 
    it "returns invalid when #{f.to_s} is missing" do 
              cr = CarRegistration::Vehicle.new(@user, p)
        cr.valid?
    end
  end
end

基于注释更新:我还想在其他测试中使用值数组哈希。如果我按照规定把它放在循环中,我仍然需要在其他地方重复它。还有其他建议吗?

更新:我尝试使用let(),

  describe "When one field is missing" do

        let(:user) {Factorybot.create(:user)}
        let(:attributes) = {{"has_car"=>"true", "has_truck"=>"true", "has_boat"=>"true", "color"=>"blue value", "size"=>"large value"}}

      attributes do |f|
        p = attributes.except(f) 
        it "returns invalid when #{f.to_s} is missing" do 
                  cr = CarRegistration::Vehicle.new(user, p)
            cr.valid?
        end
      end
  end

但得到以下错误。

attributes不适用于示例组(例如describecontext区块)。它只能从单个示例(例如it块)或在示例范围内运行的构造(例如beforelet等)中获得。

ruby-on-rails rspec-rails ruby-on-rails-5.2
3个回答
1
投票

在任何一个片段中,您都不需要在规范中使用attributes。这是生成规格的数据。因此,它必须高于一级。

describe "When one field is missing" do

  let(:user) { Factorybot.create(:user) }

  attributes = { "has_car" => "true", "has_truck" => "true", "has_boat" => "true", "color" => "blue value", "size" => "large value" }

  attributes do |f|
    p = attributes.except(f)
    it "returns invalid when #{f.to_s} is missing" do
      cr = CarRegistration::Vehicle.new(user, p)
      cr.valid?
    end
  end
end

0
投票

您似乎已经认识到,根据您链接到的其他SO帖子,您无法在描述块中引用您的实例变量。只需将其设置为本地变量即可。


0
投票

使用let

describe "When one field is missing" do
  let(:user) {Factorybot.create(:user)}
  let(:attributes) = {{"has_car"=>"true", "has_truck"=>"true", "has_boat"=>"true", "color"=>"blue value", "size"=>"large value"}}
  ## The variables are used INSIDE the it block.
  it "returns invalid when a key is missing" do
    attributes do |f|
      p = attributes.except(f)
      cr = CarRegistration::Vehicle.new(user, p)
      expect(cr.valid?).to eq(true)  # are you testing the expectation? Added this line.    
    end
  end
end

就个人而言,我不喜欢编写测试(如上所述)可能由于多种原因而失败。塞尔吉奥是对的。但是如果你想使用let,你必须在it块中使用它 - 这个例子表明了这一点。

© www.soinside.com 2019 - 2024. All rights reserved.