user1185081
user1185081

Reputation: 2118

How to instanciate a parent-child relation with Factory-Bot on Ruby on Rails5.2?

I am writing tests for my BusinessArea model. As its main caracteristic, a business area belongs to a playground:

class BusinessArea < ApplicationRecord
belongs_to :parent,       class_name: "Playground",   foreign_key: "playground_id"

Which has to be tested in some related business cases.

Thus I need to create a business_area instance based on its parent association. So I tried the following:

FactoryBot.define do
  factory :business_area do
    association :parent,  factory: :playground
    name                {{"en":"Test Business Area", "fr":"Business Area de test"}}
    code                {Faker::Code.unique.rut}
    description         {{"en":"This is a test Business Area used for unit testing"}}
    created_by          {"Fred"}
    updated_by          {"Fred"}
    status_id           {0}
    owner_id            {0}
    responsible_id      {0}
    deputy_id           {0}
    reviewer_id         {0}
    playground_id       {parent.id}
  end
end

I would expect the parent association to be created too, and parent.id to be available to initialise the playground_id attribute. But playground_id remains null.

How shall I handle this?

Upvotes: 0

Views: 176

Answers (1)

nitsas
nitsas

Reputation: 1135

I think that you don't need to set playground_id in factory :business_area. You've already defined association :parent, factory: :playground, so FactoryBot knows how to set the foreign key.

FactoryBot.define do
  factory :business_area do
    association :parent,  factory: :playground
    # ... rest of the attributes

    # playground_id { parent.id }   # <-- Try skipping this line
  end
end

# Then in the specs this should work:
playground = FactoryBot.create(:playground)
business_area = FactoryBot.create(:business_area, parent: playground)
business_area.playground_id == playground.id
# => true

Make sure you're using FactoryBot.create(...) instead of FactoryBot.build(...), otherwise the IDs won't be set until you save the records.

Upvotes: 0

Related Questions