FactoryBot là gì? Khác gì với fixture truyền thống?
FactoryBot là gì? Khác gì với fixture truyền thống?
FactoryBot là thư viện tạo dữ liệu test bằng "factory" (mô tả cách dựng object) thay vì file YAML fixtures tĩnh.
# spec/factories/users.rb
FactoryBot.define do
factory :user do
sequence(:email) { |n| "user#{n}@example.com" }
name { Faker::Name.name }
role { :member }
trait :admin do
role { :admin }
end
factory :user_with_posts do
transient { posts_count { 3 } }
after(:create) { |user, ev| create_list(:post, ev.posts_count, author: user) }
end
end
end
create(:user) # lưu DB
build(:user, name: "An") # chưa lưu
build_stubbed(:user) # giả lập, không chạm DB (nhanh)
create(:user, :admin)
create_list(:user, 5)
attributes_for(:user) # hash thuộc tính
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.