Updated : August 2011 to work with Factory Girl 2.0.5
It’s been annoying me for some time that when I hit reload! in the Rails console my factories stop working, or point to the wrong class. This wasn’t a real issue until I started using Devise.
Devise uses a mapping between classes and routes, so when a factory built object comes through to Devise after a console reload, or a class redefinition then it will fail. This is commonly the case in development and test environments.
I sat down with a colleague today (thanks Darcy) and we found the appropriate place to reload Factories to have it all work.
This is the code we put into my application.rb :
ActionDispatch::Callbacks.after do
# Reload the factories
return unless (Rails.env.development? || Rails.env.test?)
unless FactoryGirl.factories.blank? # first init will load factories, this should only run on subsequent reloads
FactoryGirl.factories.clear
FactoryGirl.find_definitions
end
end
After that everything just worked and I can hit reload! in the console without any issue.
Chuck J Hardy
Mar 4, 2011
Thanks Aaron and Darcy. Works like a charm. Keep it up.
Larry
Aug 23, 2011
Hi,
I am using the Rails Console and making changes to my Factories and was getting annoyed with having to shut down and restart the console every time I changed something in the factory definition file, so this fix looked like a really good deal.
Unfortunately, it did not work for me. (I am using Rails 3.0.9 and FactoryGirl 2.0.4)
I changed one of my factories and when I entered “reload!” it complained about another factory already being loaded (that I hadn’t used at all).
The error is at the bottom of my post. I am wondering if I am doing something wrong or else perhaps your fix was for a FactoryGirl 1.x version and it no longer works with the new 2.x ?
I know you’re probably busy, so any insights would be appreciated. And if you can’t, that’s cool, too. At least I brought this to your attention.
Thanks for taking the time to post your solution,
Larry
========== ERROR =========
>> reload!
Reloading…
FactoryGirl::DuplicateDefinitionError: Already defined: district
Aaron
Aug 30, 2011
Hi there, reloading factories has changed a little lately; it’s a lot easier!
All you need to do is :
FactoryGirl.factories.clear
FactoryGirl.find_definitions
This will then give you factories reloaded as the code did before.
Michael
Dec 15, 2011
Thanks! This works like charm. Your commands won’t work when using traits though. Adding “FactoryGirl.traits.clear” after clearing the factories fixes that. Thanks for the great advice!
Nicolas Buduroi
Mar 5, 2013
I hadn’t had any success with with Callbacks using Rails 3.2, I’ve resorted to using the Reloader (which somewhat makes more sense).
ActionDispatch::Reloader.to_cleanup do
return unless Rails.env.development?
unless FactoryGirl.factories.blank?
FactoryGirl.factories.clear
FactoryGirl.traits.clear
FactoryGirl.find_definitions
end
end
Luis Merino
Apr 3, 2013
Very useful, thanks for sharing!