how to access has_many models that is created in before clause
Asked Answered
E

2

13

There is a Company class that has_many QuarterValue, and I have a RSpec test for it.

  let(:company) { Company.create }
  describe 'company has many quarter values' do
    before do
      10.times { create(:quarter_value, company: company) }
    end
    it 'has 10 quarter values' do
      expect(company.quarter_values.count).to eq(10)
    end
  end

The test passes. My question is when I put binding.pry just above the expect matcher I can't access company.quarter_values, that returns empty array [].

How can I access has_many models object in RSpec test by using binding.pry?

spec/factories.rb

FactoryGirl.define do
  factory :company do
    sequence(:code) { |n| n + 1000 }
  end
  factory :quarter_value do
    company
  end
end
Elmerelmina answered 27/12, 2015 at 14:11 Comment(2)
What happens if you do a company.reload?Institutive
I made an app to test this and duplicated everything given the provided information and cannot replicate. When I binding pry above the expect and then in my console put company.quarter_values it returns all 10 records ... not an empty array. which is expected but doesn't jive with what you're saying.Arthromere
G
3

You need to modify your code to look like this:

let(:company) { Company.create }
describe 'company has many quarter values' do
  before do
    10.times { create(:quarter_value, company: company) }
    company.reload
  end
  it 'has 10 quarter values' do
    expect(company.quarter_values.count).to eq(10)
  end
end

The company variable you created at the start has no knowledge that it has been given any quarter_values. You need to call company.reload to update company with the new relations it was given because that instance of the Company model wasn't involved in create(:quarter_value, company: company)

Gonnella answered 18/1, 2016 at 19:45 Comment(0)
O
2

You should reload the company object in either before block or inside the pry session, while debugging.

It

Reloads the attributes of this object from the database.

Orola answered 14/1, 2016 at 16:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.