Setup Factory Bot in Rails

Table of contents
Factory Bot is a library for setting up test data objects in Ruby. Today we will be setting up Factory Bot in Rails which uses RSpec for testing. If you are using different test suite, you can view all supported configurations here.
To setup Factory Bot in Rails, we should follow the steps given below:
-
Add
factory_bot_railsto your Gemfile in :development, :test groupgroup :development, :test do gem 'factory_bot_rails' end - Install gem with
bundle install -
Create a file
spec/support/factory_bot.rband add the following configuration insideRSpec.configure do |config| config.include FactoryBot::Syntax::Methods end -
Uncomment following line from rails_helper.rb so all files inside
spec/supportare loaded automatically by rspec# Dir[Rails.root.join('spec', 'support', '**', '*.rb')].sort.each { |f| require f } Dir[Rails.root.join('spec', 'support', '**', '*.rb')].sort.each { |f| require f } -
Check factory bot rails version inside Gemfile.lock and update the gem with that version in
Gemfile. It was6.1.0while writing this tutorial, yours may be different depending on latest gem version.group :development, :test do gem 'factory_bot_rails', '~> 6.1.0' end - Run
bundle install(Optional, since nothing will change insideGemfile.lock) - Add factories folder inside
specfolder if it doesn’t already exist. You can then create factories insidespec/factoriesfolder. - Assuming you have model User, you can create
factories/users.rb -
If attributes in
userstable are firstname, lastname, email, mobile_number. Yourusersfactory will look something like this:FactoryBot.define do factory :user do first_name { 'John' } last_name { 'Doe' } email { john@email_provider.com } mobile_number { 7860945310 } end end -
You can use the
userfactory inside youruser_specslike thisrequire 'rails_helper' RSpec.describe User, type: :model do let(:user) { build(:user) } end - You can view various use cases in official documentation for using factories in your tests.
Conclusion
Factory Bot helps in reusing the same code in multiple test examples, this way you will have to write less code and as they say “Less code is always better”.
Thank you for reading. Happy coding!
References
Image Credits
- Cover Image by Anchor Lee on Unsplash
