FactoryBot is used to set up factories for testing data in Rails.
Running FactoryBot from console
FactoryBot is usually set up to run in your test environment. The fastest way to get to what you want is to run your console in the test environment
From your console:
rails console test
Once the console is running, run the following command:
require "factory_bot_rails"; include FactoryBot::Syntax::Methods; require 'faker'
Alternatively, you could also modify your gem file so that FactoryBot runs in both your development as well as test environment.
You would modify your Gemfile with the following:
group :development, :test do
gem 'factory_bot_rails'
end
Dealing with associations
Imagine having a data model with the following relationship
class Product < ActiveRecord::Base
has_many :listings
end
class Listing < ActiveRecord::Base
belongs_to :product
end
Associating an object to another object
One of the simplest ways to do this is as following:
FactoryBot.define do
factory :product do
name: { "Asus Zenpad 3" }
description: { "Fantastic 8 inch tablet for reading" }
end
factory :listing do
product
company_name: { "Canada Computers" }
price: { "289.99" }
end
In your code, you would do the following:
@product = FactoryBot.create(:product)
@product.listings << FactoryBot.create(:listing, product: @product)
Associations with lists
References:
Qiita
ThoughtBot Getting Started Guide
ThoughtBot Support for Interrelated Model Associations
Here’s how you would set up the corresponding FactoryBot
FactoryBot.define do
# listing factory
factory :listing do
company_name: { "Canada Computers" }
price: { "289.99" }
product
end
# user factory without associated listings
factory :product do
# product attributes
name: { "Asus ZenPad 3" }
description: { "Fantastic 8 inch tablet for reading" }
factory :product_with_listings do
transient do
listings_count 10
end
after(:create) do |listing, evaluator|
create_list(:listings, evaluator.listings_count, product: product)
end
end
end
end
To use the factory, you would use it in the following way:
FactoryBot.create(:products_with_litings, listing_count: 15)