Back to Repositories

Testing Add_Attribute Reserved Word Handling in factory_bot

This test suite validates the add_attribute functionality in FactoryBot, specifically focusing on handling reserved words in model attributes. It ensures proper attribute assignment both for building objects and generating attribute hashes.

Test Coverage Overview

The test suite provides comprehensive coverage of FactoryBot’s add_attribute method, specifically focusing on handling reserved words in model attributes.

  • Tests attribute assignment for reserved words like ‘title’, ‘sequence’, and ‘new’
  • Verifies functionality with both .build and .attributes_for methods
  • Ensures consistent behavior across different object creation strategies

Implementation Analysis

The testing approach employs RSpec’s describe/it blocks to organize test cases logically. The implementation uses FactoryBot’s define_model helper to create test models dynamically, demonstrating proper factory definition patterns.

  • Uses block syntax for attribute definition
  • Implements dynamic value assignment
  • Handles both object and hash-based attribute access

Technical Details

  • RSpec testing framework
  • FactoryBot factory definition DSL
  • Dynamic model definition using define_model
  • Expectation matching with RSpec matchers
  • Ruby string and boolean attribute types

Best Practices Demonstrated

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

  • Clear test case separation and organization
  • Consistent expectation formatting
  • Proper setup and model definition
  • Comprehensive edge case coverage
  • DRY factory definitions

thoughtbot/factory_bot

spec/acceptance/add_attribute_spec.rb

            
describe "#add_attribute" do
  it "assigns attributes for reserved words on .build" do
    define_model("Post", title: :string, sequence: :string, new: :boolean)

    FactoryBot.define do
      factory :post do
        add_attribute(:title) { "Title" }
        add_attribute(:sequence) { "Sequence" }
        add_attribute(:new) { true }
      end
    end

    post = FactoryBot.build(:post)

    expect(post.title).to eq "Title"
    expect(post.sequence).to eq "Sequence"
    expect(post.new).to eq true
  end

  it "assigns attributes for reserved words on .attributes_for" do
    define_model("Post", title: :string, sequence: :string, new: :boolean)

    FactoryBot.define do
      factory :post do
        add_attribute(:title) { "Title" }
        add_attribute(:sequence) { "Sequence" }
        add_attribute(:new) { true }
      end
    end

    post = FactoryBot.attributes_for(:post)

    expect(post[:title]).to eq "Title"
    expect(post[:sequence]).to eq "Sequence"
    expect(post[:new]).to eq true
  end
end