从FactoryGirl迁移到FactoryBot后RSpec出现Factory未注册错误
Let's walk through the most common fixes for this error—this is a super common gotcha when switching from FactoryGirl to FactoryBot, so you're not alone!
1. Double-Check Your Gem and Support Configs
First, make sure you've fully swapped out FactoryGirl for FactoryBot in your setup:
- Update your
Gemfileto usegem 'factory_bot_rails'(instead offactory_girl_rails), then runbundle installto pull in the new gem. - Rename your old
spec/support/factory_girl.rbfile tospec/support/factory_bot.rb, and update its content to reference FactoryBot instead of FactoryGirl:RSpec.configure do |config| config.include FactoryBot::Syntax::Methods end - Verify that your
spec/rails_helper.rbis loading all support files—you should have a line like this:
If this line is missing or commented out, your FactoryBot config won't load properly.Dir[Rails.root.join('spec', 'support', '**', '*.rb')].sort.each { |f| require f }
2. Fix Your Factory Definitions
Next, check your factory files (usually in spec/factories/):
- Replace every instance of
FactoryGirl.define dowithFactoryBot.define doin your factory files. For example, yourspec/factories/users.rbshould look like this:FactoryBot.define do factory :user do email { 'test@example.com' } password { 'securepassword123' } # Add your other user attributes here end end - Double-check for typos: Make sure the factory name is exactly
:user(not:users,User, or anything else) and that you're callingcreate(:user)orbuild(:user)correctly in your tests.
3. Clear Caches and Restart Your Test Environment
Old cached code can cause weird issues after a gem swap:
- Run
rails tmp:clearto clear Rails' temporary files and caches. - If you're using Spring (the Rails preloader), stop it with
spring stopthen re-run your tests—Spring sometimes holds onto old versions of code. - Restart your terminal or IDE to make sure no stale processes are running.
4. Verify Factory Loading in the Console
If you're still stuck, test directly in the Rails console to debug:
- Fire up
rails console -e test(to load the test environment). - Run
FactoryBot.factories.map(&:name)—this should return an array including:user.- If
:userisn't there, try manually loading your factory file with:require Rails.root.join('spec', 'factories', 'users.rb') - If loading it manually works, your
rails_helper.rbisn't including the factories correctly—double-check the require paths for your factory directory.
- If
5. Check RSpec Config Load Order
Make sure your FactoryBot support file is loaded before your RSpec tests. The standard setup loads support files first in rails_helper.rb, so if you've modified the order or moved configs to spec_helper.rb, that could be causing the issue. Stick to the standard setup where rails_helper.rb loads support files and sets up RSpec.
内容的提问来源于stack exchange,提问作者Michel Fernandes

