Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to access has_many models that is created in before clause

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
like image 685
ironsand Avatar asked Dec 27 '15 14:12

ironsand


2 Answers

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)

like image 130
Lockyy Avatar answered Oct 23 '22 14:10

Lockyy


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.

like image 28
Andrey Deineko Avatar answered Oct 23 '22 15:10

Andrey Deineko