Missing association in trait leads to additional factory usage

Everyone can contribute. Help move this issue forward while earning points, leveling up and collecting rewards.

  • Close this issue

Problem

In situations where we are using nested traits with association, it is ending up in using additional factory. It seems that we are having N+1 usage of factories. In the example below, we are using the :project factory two times.

Example

trait :with_jira_integration do
  has_external_issue_tracker { true }

  jira_integration
end
RSpec.describe "Foo" do
  it "creates a project" do
    create(:project, :with_jira_integration)
  end
end

Output

 Total: 6
 Total top-level: 2
 Total time: 00:01.603 (out of 00:15.824)
 Total uniq factories: 4

   total   top-level     total time      time per call      top-level time               name

       2           1        2.2575s            1.1288s             1.5919s            project
       2           0        0.4733s            0.2366s             0.0000s          namespace
       1           1        0.0115s            0.0115s             0.0115s            license
       1           0        0.8094s            0.8094s             0.0000s   jira_integration

Solution

We could use after :create strategy, which is conflicting with #262624:

Example

trait :with_jira_integration do
  has_external_issue_tracker { true }
  
  after :create do |project|
    create(:jira_integration, project: project)
  end
end

or we could go with interconnected-associations, which might require additional changes on a model or factory level due to validations:

trait :with_jira_integration do
  has_external_issue_tracker { true }

  jira_integration { association :jira_integration, project: instance }
end

Output

 Total: 4
 Total top-level: 2
 Total time: 00:00.871 (out of 00:14.044)
 Total uniq factories: 4

   total   top-level     total time      time per call      top-level time               name

       1           1        0.0075s            0.0075s             0.0075s            license
       1           1        0.8636s            0.8636s             0.8636s            project
       1           0        0.2771s            0.2771s             0.0000s          namespace
       1           0        0.1056s            0.1056s             0.0000s   jira_integration

/cc @splattael

Edited Sep 28, 2025 by 🤖 GitLab Bot 🤖
Assignee Loading
Time tracking Loading