🏭

FactoryBot

테스트 데이터를 깔끔하게 생성

FactoryBot은 테스트에서 필요한 데이터를 생성하는 라이브러리입니다.

# spec/factories/users.rb
FactoryBot.define do
  factory :user do
    name { 'Test User' }
    email { Faker::Internet.email }  # Faker gem으로 랜덤 데이터
    password { 'password123' }

    trait :admin do
      after(:create) { |user| user.add_role(:admin) }
    end

    trait :with_posts do
      after(:create) do |user|
        create_list(:post, 3, user: user)
      end
    end
  end
end

사용:

create(:user)                    # DB에 저장
build(:user)                     # 메모리에만 생성 (저장 안 함)
create(:user, :admin)            # trait 적용
create(:user, name: 'Custom')    # 속성 오버라이드
create_list(:user, 5)            # 5개 생성

Fixture vs Factory:

  • Fixture: YAML 파일에 고정 데이터 (Rails 기본)

  • Factory: 코드로 동적 데이터 생성 (더 유연)

핵심 포인트

1

spec/factories/ 디렉토리에 팩토리 정의 파일 생성

2

factory :model do ... end 블록으로 기본 속성 정의

3

trait :name do ... end 로 변형 정의 (admin, with_posts 등)

4

create(:model) — DB에 저장된 인스턴스 생성

5

build(:model) — 저장하지 않은 인스턴스 생성 (빠름)

6

association — 관련 모델도 자동 생성

장점

  • 코드로 정의 → 유연하고 동적
  • trait로 변형 쉽게 관리
  • association 자동 처리
  • Faker gem과 결합하여 현실적인 데이터

단점

  • 팩토리가 복잡해지면 관리 어려움
  • create 남용 시 테스트 속도 저하 (build 권장)
  • 순환 참조 주의
  • 암묵적 association 생성이 혼란 유발 가능

사용 사례

RSpec 테스트 데이터 생성 trait로 역할별 사용자 생성 association으로 관계 데이터 자동 생성 create_list로 대량 데이터 생성