Acts As Tree: assigning parent to a child with letting parent know about it?

59 Views Asked by At

When I manually assign a parent to a child like this:

parent = create :rule # I'm using FactoryBot to create test data
child = create :rule, parent: parent

Then the parent doesn't know about it:

parent.children # => []

How can I make sure that the parent gets to know about the new child? At the moment, I manually assign the child to the parent:

parent.children << child

But this feels quirky. Is there a better way of doing it?

1

There are 1 best solutions below

0
On

In your factory:

## spec/factories/rules.rb

factory :rule do
  attribute_1 { 'bla' }
  ...

  trait :with_child do
  association :child, factory :rule
end

This will let you call from your spec:

child = create(:rule, :with_child).children.first

And will create both your parent and child in one line, or if you need both assigned to a varaible:

parent = create(:rule, :with_child)
child = parent.children.first