This guides you through adding the test data fixture utility factory_bot to your Ruby on Rails RSpec project.
To install factory_bot you will need to...
- Add the factory_bot_rails gem to your Rails RSpec project
- Configure factory_bot_rails to be used by RSpec Rails
π π I originally learned this from these posts...
You need to add the factory_bot_rails
gem to your Gemfile
but really only need it for development and test.
-
Edit your
Gemfile
and addgem 'factory_bot_rails'
to just:development, :test
group
, for example...group :development, :test do # See https://guides.rubyonrails.org/debugging_rails_applications.html#debugging-with-the-debug-gem gem "debug", platforms: %i[ mri windows ] # Add RSpec and test utilities and tools gem 'factory_bot_rails' gem 'rspec-rails' end
-
Run
bundle install
to install thefactory_bot_rails
gembundle install
βοΈ If you are doing container-native development, be sure to run your
bundle
commands in the container environment
You need to configure RSpec Rails to use factory_bot fixtures and methods in its specs.
You can add the factory_bot configuration directly to your
rails_helper
file, but you may find it cleaner to create a
separate file and include it.
-
Create a new
spec/support/config/
directory if you do not already have onemkdir -p spec/support/config
-
Create a new
spec/support/config/factory_bot.rb
filetouch spec/support/config/factory_bot.rb
-
Edit your
spec/support/config/factory_bot.rb
file to have the following...# frozen_string_literal: true # Add Factory Bot Methods to spec DSL RSpec.configure do |config| config.include FactoryBot::Syntax::Methods end
-
Save your edited
spec/support/config/factory_bot.rb
file -
Edit your
spec/rails_helper.rb
file and addrequire 'support/config/factory_bot'
, for example...# Add additional requires below this line. Rails is not loaded until this point! require 'support/config/factory_bot'
-
Save your edited
spec/rails_helper.rb
file
π You should now be able to use the factory_bot methods to create your factory_bot test data.