24
Factory Bot cheatsheet
source link: https://devhints.io/factory_bot
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Introduction
Factory Bot is a helper for writing factories for Ruby tests. It was previously known as Factory Girl. For older versions, use FactoryGirl
instead of FactoryBot
.
Defining factories
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
See: Defining factories
Extra options
Custom class names
factory :user, class: 'User' do
···
end
Aliases
factory :user, aliases: [:author] do
···
end
Using
Build a model
FactoryBot.build(:user)
Other ways
build(:user) # → model (not saved)
create(:user) # → model (saved)
attributes_for(:user) # → hash
build_stubbed(:user) # stubbed out attributes
With options
build(:user, name: 'John')
Lists
create_list(:user, 3)
build_list(:user, 3)
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK