Back to Repositories

Testing Factory Alias Configuration and Overrides in Factory Bot

This test suite validates Factory Bot’s alias functionality and attribute overrides in factory definitions. It examines how aliases are configured and how they interact with model attributes during object creation, ensuring proper handling of attribute mappings and overrides.

Test Coverage Overview

The test suite covers Factory Bot’s alias system and attribute override capabilities. It verifies:

  • Alias registration using regex patterns
  • Model attribute definitions and mappings
  • Factory attribute overrides during object creation
  • Interaction between aliases and explicit attribute values

Implementation Analysis

The testing approach uses RSpec’s describe/before pattern to set up the test environment. It implements:

  • Dynamic model definition with specific attributes
  • Factory configuration with alias mappings
  • Subject-based testing with attribute assertions
  • RSpec’s ‘its’ syntax for property verification

Technical Details

Testing infrastructure includes:

  • RSpec as the testing framework
  • Factory Bot for test data generation
  • Dynamic model definition capabilities
  • Regular expression based alias configuration
  • Subject/should expectation syntax

Best Practices Demonstrated

The test exhibits several quality testing practices:

  • Isolated test setup with clear arrangement
  • Focused test scenarios with single responsibility
  • Clear separation of configuration and assertions
  • Effective use of RSpec’s declarative syntax
  • Comprehensive validation of both positive and negative cases

thoughtbot/factory_bot

spec/acceptance/aliases_spec.rb

            
describe "aliases and overrides" do
  before do
    FactoryBot.aliases << [/one/, "two"]

    define_model("User", two: :string, one: :string)

    FactoryBot.define do
      factory :user do
        two { "set value" }
      end
    end
  end

  subject { FactoryBot.create(:user, one: "override") }
  its(:one) { should eq "override" }
  its(:two) { should be_nil }
end