Back to Repositories

Testing Private Attribute Handling in factory_bot

This test suite examines FactoryBot’s handling of private attributes in Ruby classes. It specifically verifies that attempting to set private attributes through factory definitions raises appropriate errors, ensuring proper encapsulation is maintained.

Test Coverage Overview

The test coverage focuses on validating FactoryBot’s behavior when interacting with private attributes defined in Ruby classes. It tests:

  • Private attribute accessor handling
  • Error raising for unauthorized access
  • Factory definition validation with private members
  • Class encapsulation enforcement

Implementation Analysis

The testing approach uses RSpec’s expect block syntax to verify error handling. It employs dynamic class definition with a private attr_accessor and attempts to set it through a FactoryBot factory definition, expecting a NoMethodError to be raised when the private setter is accessed.

Technical Details

Testing tools and configuration:

  • RSpec testing framework
  • FactoryBot gem for test data generation
  • Dynamic class definition using define_class helper
  • Ruby’s private method access controls

Best Practices Demonstrated

The test demonstrates several quality testing practices:

  • Explicit error expectation testing
  • Proper isolation of test cases
  • Clear setup of test prerequisites
  • Verification of object-oriented principles
  • Appropriate use of RSpec’s error matching syntax

thoughtbot/factory_bot

spec/acceptance/private_attributes_spec.rb

            
describe "setting private attributes" do
  it "raises a NoMethodError" do
    define_class("User") do
      private

      attr_accessor :foo
    end

    FactoryBot.define do
      factory :user do
        foo { 123 }
      end
    end

    expect {
      FactoryBot.build(:user)
    }.to raise_error NoMethodError, /foo=/
  end
end