当我像这样手动将父母分配给孩子时:
parent = create :rule # I'm using FactoryBot to create test data
child = create :rule, parent: parent
然后父母不知道:
parent.children # => []
我怎样才能确保父母了解新孩子?目前,我手动将孩子分配给父母:
parent.children << child
但这感觉很古怪。有更好的方法吗?
当我像这样手动将父母分配给孩子时:
parent = create :rule # I'm using FactoryBot to create test data
child = create :rule, parent: parent
然后父母不知道:
parent.children # => []
我怎样才能确保父母了解新孩子?目前,我手动将孩子分配给父母:
parent.children << child
但这感觉很古怪。有更好的方法吗?
在您的工厂:
## spec/factories/rules.rb
factory :rule do
attribute_1 { 'bla' }
...
trait :with_child do
association :child, factory :rule
end
这将让您从规范中调用:
child = create(:rule, :with_child).children.first
并将在一行中创建您的父母和孩子,或者如果您需要将两者都分配给一个变量:
parent = create(:rule, :with_child)
child = parent.children.first