RSpec - Uninitialized variable outside of tests

我的未来我决定 提交于 2020-01-15 02:45:07

问题


Sorry, I don't know how to word the title better, but here is a general idea of my test:

describe Model do
  let(:model) { FactoryGirl.create(:model) }
  subject { model }

  it { should be_valid }

  model.array_attribute.each do |attribute|
    context "description" do
      specify { attribute.should == 1 }
    end
  end
end

The problem is that at the line model.array_attribute.each do |attribute|, I get an error of undefined local variable or method model. I know that the let(:model) is working because the validation (among other things) works fine. I suspect that the issue is because it's being called outside of any actual test (ie. specify, it, etc.).

Any ideas on how to get this to work?


回答1:


model is unknown here because it's only evaluated inside the specs block context.

Do something like:

describe Model do
  def model
    FactoryGirl.create(:model)
  end

  subject { model }

  it { should be_valid }

  model.array_attribute.each do |attribute|
    context "description" do
      specify { attribute.should == 1 }
    end
  end
end

BTW, there is a nice read here.




回答2:


I solved this with the following code:

describe Model do
  let(:model) { FactoryGirl.create(:model) }
  subject { model }

  it { should be_valid }

  it "description" do
    model.array_attribute.each do |attribute|
      attribute.should == 1
    end
  end
end


来源:https://stackoverflow.com/questions/10609340/rspec-uninitialized-variable-outside-of-tests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!