Nick
Nick

Reputation: 9866

RSpec - Uninitialized variable outside of tests

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?

Upvotes: 2

Views: 2119

Answers (2)

Nick
Nick

Reputation: 9866

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

Upvotes: 1

apneadiving
apneadiving

Reputation: 115511

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.

Upvotes: 2

Related Questions