FactoryBot Rails
FactoryBot is a Ruby library for setting up Ruby objects as test data in a test suite. Specifically, FactoryBot Rails is an extension of FactoryBot designed to work seamlessly with Ruby on Rails applications.
In the context of testing Rails applications, FactoryBot Rails provides a convenient way to define and create factories for ActiveRecord models.
Factories are used to generate instances of model objects with predefined attributes, making it easier to set up test data for various scenarios.
Add to the Gemfile
According to the documentation, add factory_bot_rails
to your Gemfile in both the test and development groups:
group :development, :test do
gem 'rspec-rails'
gem 'factory_bot_rails'
gem "debug", platforms: %i[ mri mingw x64_mingw ]
end
Install the dependencies
bundle install
Output
Configure FactoryBot Rails
The next parts is to configure FactoryBotRails
.
Create a folder
mkdir spec/support
Create the configuration file
touch spec/support/factory_bot.rb
Add the configuration
# spec/support/factory_bot.rb
RSpec.configure do |config|
config.include FactoryBot::Syntax::Methods
end
This configures RSpec to include FactoryBot methods (like create
, build
, etc.) in your tests and ensures that FactoryBot factories are loaded before the test suite runs.
Let's test
Create a rspec test file
rails generate rspec:model Author
Use the create
method
We don't have any factories yet, but let's try to use the create
method anyway.
# spec/models/author_spec.rb
require 'rails_helper'
RSpec.describe Author, type: :model do
it 'creates a valid author object using FactoryBot' do
author = FactoryBot.create(:author)
expect(author).to be_valid
expect(author.persisted?).to eq(true)
end
end
Run the tests
bundle exec rspec spec/models/author_spec.rb -fd
output
Great, it tried to create an object using FactoryBot.
Use the build
method
# spec/models/author_spec.rb
RSpec.describe Author, type: :model do
it 'builds a valid author object using FactoryBot' do
author = FactoryBot.build(:author, name: 'John Doe')
expect(author).to be_valid
author.save
expect(author.persisted?).to eq(true)
end
end
Output of the complete code
Run the tests
bundle exec rspec spec/models/author_spec.rb -fd
Output
Create a factory
Create the factories
folder
mkdir spec/factories
Output
Create the file
touch spec/factories/authors.rb
Output
Add the factory
# spec/factories/authors.rb
FactoryBot.define do
factory :author do
name { 'Toby Flanderson' }
end
end
Run the tests
The error messages so far have indicated that we don't have registered factories, but this time we do.
Let's run the tests; all the tests should fail.
Run
bundle exec rspec spec/models/author_spec.rb -fd
Output
Done
Reach me out
Final thoughts
Thank you for reading this article.
If you have any questions, thoughts, suggestions, or corrections, please share them with us.
We appreciate your feedback and look forward to hearing from you.