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?
FactoryGirl.define do
factory :company do
sequence(:code) { |n| n + 1000 }
end
factory :quarter_value do
company
end
end
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With