Factory Bot Flashcards
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 end
How 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?
- FactoryBot.create(:project) # saves to a database
- FactoryBot.build(:project) # doesn’t save to a database
- FactoryBot.build_stubbed(:project) # doesn’t save to a database and create fake id
- FactoryBot.attributes_for(:project) # returns hash with all factory bot methods
How to create a list of factories?
- FactoryBot.create_list(:animal, 3)
How to create only 2 factories?
- FactoryBot.create_pair(:animal)
How to create uniq value for the factory field?
sequence(:name) { |n| "Name #{n}" } # will return Name 1, Name 2 etc
How 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 end
How 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