如何访问在 before 子句中创建的 has_many 模型
how to access has_many models that is created in before clause
有一个 Company
class 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
匹配器上方时,我无法访问 company.quarter_values
,那个 returns 空数组 []
.
如何使用 binding.pry
在 RSpec
测试中访问 has_many
模型对象?
spec/factories.rb
FactoryGirl.define do
factory :company do
sequence(:code) { |n| n + 1000 }
end
factory :quarter_value do
company
end
end
调试时,您应该 reload
before
块中或 pry
会话中的 company
对象。
它
Reloads the attributes of this object from the database.
您需要将代码修改为如下所示:
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_values
。
您需要调用 company.reload
以使用给定的新关系更新公司,因为 Company
模型的实例未涉及 create(:quarter_value, company: company)
有一个 Company
class 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
匹配器上方时,我无法访问 company.quarter_values
,那个 returns 空数组 []
.
如何使用 binding.pry
在 RSpec
测试中访问 has_many
模型对象?
spec/factories.rb
FactoryGirl.define do
factory :company do
sequence(:code) { |n| n + 1000 }
end
factory :quarter_value do
company
end
end
调试时,您应该 reload
before
块中或 pry
会话中的 company
对象。
它
Reloads the attributes of this object from the database.
您需要将代码修改为如下所示:
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_values
。
您需要调用 company.reload
以使用给定的新关系更新公司,因为 Company
模型的实例未涉及 create(:quarter_value, company: company)