What is FactoryBot?
FactoryBot is a Ruby library for setting up test data efficiently. Instead of manually creating test records in each test case, FactoryBot provides a factory-based approach to generate test data dynamically.
Why Use FactoryBot?
Installation & Setup
FactoryBot is already included in the Gemfile
under the development
and test
groups:
group :development, :test do
gem "factory_bot_rails"
end
Run bundle install
to install the gem.
To enable FactoryBot syntax shortcuts, it has been configured in spec/rails_helper.rb
:
RSpec.configure do |config|
config.include FactoryBot::Syntax::Methods
end
This allows you to write create(:expense)
instead of FactoryBot.create(:expense)
.
Factory Directory & File Structure
FactoryBot stores factory definitions in the spec/factories
directory.
spec/factories/expenses.rb
: Defines how an Expense
object should be generated for tests.spec/factories
.Example: Expense Factory
A factory for the Expense
model has already been created:
FactoryBot.define do
factory :expense do
name { "Internet Bill" }
amount { 69.00 }
date { Date.new(2025, 1, 31) }
category { "Utilities" }
end
end
This allows for easy test data creation:
let(:expense) { create(:expense) } # Creates a valid Expense object
How to Use FactoryBot in Tests
expense = create(:expense)
expenses = create_list(:expense, 5)
Troubleshooting Common Issues
uninitialized constant FactoryBot
factory_bot_rails
is installed and included in the test environment.undefined method create
config.include FactoryBot::Syntax::Methods
is present in rails_helper.rb
.