مرجع سريع

ورقة غش مكتبة Factory Bot في Ruby

دليل مرجعي سريع لمكتبة Factory Bot في Ruby: تعريف المصانع، العلاقات، السمات المخصصة، التسلسلات، والسمات العابرة.

· تاريخ النشر

Factory Bot هي مكتبة شائعة لإنشاء بيانات الاختبار كبديل مرن للتركيبات الثابتة (Fixtures) في Ruby و Rails.

تعريف المصانع واستراتيجيات البناء (Definition & Strategies)

FactoryBot.define do
  factory :user do
    first_name { 'John' }
    last_name  { 'Doe' }
    birthdate  { 21.years.ago }
    admin      { false }

    sequence(:username) { |n| "user#{n}" }
  end
end
# Build strategies
build(:user)           # -> model instance (not saved)
create(:user)          # -> model instance (saved to database)
attributes_for(:user)  # -> hash of attributes
build_stubbed(:user)   # stubbed out attributes (no DB hits)

# Override attributes & batch creation
build(:user, name: 'John')
create_list(:user, 3)
build_list(:user, 3)

العلاقات وروابط النماذج (Associations)

factory :post do
  association :author, factory: :user
  association :author, factory: [:user, :admin]
end
factory :post do
  after :create do |post|
    create :theme, post: post             # has_one
    create_list :comment, 3, post: post   # has_many
  end
end

السمات والوراثة والسمات العابرة (Traits & Inheritance)

factory :user do
  trait :admin do
    admin { true }
  end

  transient do
    upcased { true }
  end

  after :create do |user, options|
    user.name.upcase! if options.upcased
  end
end

create :user, :admin
create :user, upcased: true
# Inheritance
factory :sample_user, parent: :user do
  first_name { FFaker::Name.first_name }
end

أوراق غش ذات صلة

موضوعات ذات صلة