当我像这样手动将父母分配给孩子时:
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