Back to Repositories

Testing FactoryBot Create Pair Implementation in factory_bot

This test suite examines FactoryBot’s create_pair functionality for generating multiple test instances simultaneously. The tests verify the creation of Post model instances with predefined attributes and validate both object persistence and default value assignment.

Test Coverage Overview

The test suite provides comprehensive coverage of FactoryBot’s create_pair method functionality.

Key areas tested include:
  • Multiple instance creation verification
  • Persistence validation of created records
  • Default attribute assignment across instances
  • Array length validation for paired objects

Implementation Analysis

The testing approach uses RSpec’s describe/context structure to organize test scenarios around FactoryBot’s create_pair method. The implementation leverages RSpec’s subject mechanism and its expectations syntax for clear test definitions.

Notable patterns include:
  • Dynamic model definition using define_model
  • Factory definition with dynamic attribute values
  • Subject-based testing for multiple assertions

Technical Details

Testing tools and configuration:
  • RSpec as the testing framework
  • FactoryBot for test data generation
  • Dynamic model definition for test isolation
  • Random number generation for position attributes
  • String literals for title attributes

Best Practices Demonstrated

The test suite exemplifies several testing best practices in Ruby and RSpec.

Notable practices include:
  • Proper test isolation through before blocks
  • Clear context separation for different test scenarios
  • DRY testing using shared subjects
  • Explicit expectations for object state verification
  • Comprehensive validation of multiple object attributes

thoughtbot/factory_bot

spec/acceptance/create_pair_spec.rb

            
describe "create multiple instances" do
  before do
    define_model("Post", title: :string, position: :integer)

    FactoryBot.define do
      factory(:post) do |post|
        post.title { "Through the Looking Glass" }
        post.position { rand(10**4) }
      end
    end
  end

  context "without default attributes" do
    subject { FactoryBot.create_pair(:post) }

    its(:length) { should eq 2 }

    it "creates all the posts" do
      subject.each do |record|
        expect(record).not_to be_new_record
      end
    end

    it "uses the default factory values" do
      subject.each do |record|
        expect(record.title).to eq "Through the Looking Glass"
      end
    end
  end
end