Factory Bot Flashcards

1
Q

How to install factory_bot?

A
# install gem 
  gem 'factory_bot_rails'
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How to generate a factory?

A

rails g factory_bot:model task

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How to define base factory structure?

A
# spec/factories/model_names.rb
FactoryBot.define do
  factory :model_name do

end
end

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How to add fields to the factory?

A
FactoryBot.define do
  factory :task do
    name { 'name' }
    age { 1 } 
  end
end
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How to avoid using FactoryBot prefix every time? (just create instead of FactoryBot.create)

A

RSpec.configure do |config|
config.include FactoryBot::Syntax::Methods
end

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How to refer to a previously assigned value in the factory?

A

factory :animal do
age { 1 }
name { “name #{age}” }
end

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What are 4 ways to create factory_bot object?

A
  • 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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How to create a list of factories?

A
  • FactoryBot.create_list(:animal, 3)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How to create only 2 factories?

A
  • FactoryBot.create_pair(:animal)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How to create uniq value for the factory field?

A
sequence(:name) { |n| "Name #{n}" } 
# will return Name 1, Name 2 etc
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How to overwrite parameters for the factory and define the new one inside the factory? ( 2 ways )

A
# 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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How to group attributes in a single chunk of information?

A

trait :old do
age { 100 }
end

create(:animal, :old)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How to add polymorphic association?

A
FactoryBot.define do
  factory :versions_employee
    event { 'update' }
    association :item, factory: :employee
  end
end
How well did you know this?
1
Not at all
2
3
4
5
Perfectly