有一个公司类has_many QuarterValue,我有一个RSpec测试.
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
测试通过我的问题是当我将binding.pry放在expect matcher上方时,我无法访问company.quarter_values,返回空数组[].
如何使用binding.pry在RSpec测试中访问has_many模型对象?
投机/ factories.rb
FactoryGirl.define do factory :company do sequence(:code) { |n| n + 1000 } end factory :quarter_value do company end end
解决方法
您需要修改代码,如下所示:
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
您在开始创建的公司变量不知道它已经被赋予了任何quarter_value.您需要调用company.reload来更新公司,因为该公司模型的实例没有涉及到create(:quarter_value,company:company)