Back to Repositories

Testing Child-Before-Parent Factory Definitions in Factory Bot

This test suite examines FactoryBot’s capability to handle child factory definitions that precede their parent factory definitions. It validates the flexibility of factory inheritance and demonstrates how FactoryBot maintains proper relationships between parent and child factories regardless of their definition order.

Test Coverage Overview

The test suite focuses on validating FactoryBot’s factory inheritance mechanism, specifically testing the scenario where a child factory (admin) is defined before its parent factory (user). Key areas covered include:

  • Parent-child factory relationships
  • Attribute inheritance between factories
  • Order-independent factory definitions
  • Boolean attribute handling

Implementation Analysis

The testing approach employs RSpec to verify FactoryBot’s factory definition flexibility. The implementation uses define_model to set up a User model with specific attributes, then defines factories using FactoryBot.define. The test demonstrates how FactoryBot correctly resolves factory inheritance regardless of definition order.

  • Factory inheritance patterns
  • Dynamic attribute assignment
  • Model definition using define_model

Technical Details

Testing tools and configuration include:

  • RSpec testing framework
  • FactoryBot for test data generation
  • define_model helper for model creation
  • Boolean attribute validation
  • Factory inheritance configuration

Best Practices Demonstrated

The test exemplifies several testing best practices in factory definition and inheritance:

  • Clear separation of model and factory definitions
  • Explicit parent-child relationships
  • Focused test assertions
  • Clean factory attribute definitions
  • Efficient use of boolean flags

thoughtbot/factory_bot

spec/acceptance/define_child_before_parent_spec.rb

            
describe "defining a child factory before a parent" do
  before do
    define_model("User", name: :string, admin: :boolean, email: :string, upper_email: :string, login: :string)

    FactoryBot.define do
      factory :admin, parent: :user do
        admin { true }
      end

      factory :user do
        name { "awesome" }
      end
    end
  end

  it "creates admin factories correctly" do
    expect(FactoryBot.create(:admin)).to be_admin
  end
end