How to install factory_bot?
# install gem gem 'factory_bot_rails'
How to generate a factory?
rails g factory_bot:model task
How to define base factory structure?
# spec/factories/model_names.rb FactoryBot.define do factory :model_name do
end
end
How to add fields to the factory?
FactoryBot.define do
factory :task do
name { 'name' }
age { 1 }
end
endHow to avoid using FactoryBot prefix every time? (just create instead of FactoryBot.create)
RSpec.configure do |config|
config.include FactoryBot::Syntax::Methods
end
How to refer to a previously assigned value in the factory?
factory :animal do
age { 1 }
name { “name #{age}” }
end
What are 4 ways to create factory_bot object?
How to create a list of factories?
How to create only 2 factories?
How to create uniq value for the factory field?
sequence(:name) { |n| "Name #{n}" }
# will return Name 1, Name 2 etcHow to overwrite parameters for the factory and define the new one inside the factory? ( 2 ways )
# use inheritance
# first way
factory :animal do
age { 1 }
name { 'name' }
end
factory :old_animal, parent: :animal do
age { 100 }
end
# another way
factory :animal do
age { 1 }
name { 'name' }factory :old_animal do
age { 100 }
end endHow to group attributes in a single chunk of information?
trait :old do
age { 100 }
end
create(:animal, :old)
How to add polymorphic association?
FactoryBot.define do
factory :versions_employee
event { 'update' }
association :item, factory: :employee
end
end