问题
I want that when I make changes in factories, I see them in rails console without restarting all console.
I've found some lines and tested them with a poor understanding of what's going on, documentation isn't clear for me.:
FactoryGirl.reload
I've also tested:
> FactoryGirl.factories.clear
> FactoryGirl.find_definitions # also tested FactoryGirl.factories.find_definitions
# but NoMethodError is raised
=> ActiveRecord::RecordNotFound: Couldn't find Address with ID=277 Torphy Squares
回答1:
You can also use reload!
to reload the console environment but it doesn't reload the factories. Use FactoryGirl.reload
to reload the Factory definitions. It (re)loads those definitions from the following locations (see the documentation):
test/factories.rb
spec/factories.rb
test/factories/*.rb
spec/factories/*.rb
The other commands you mention are used to clear and load the definitions. FactoryGirl.factories.clear
clears all loaded Factory definitions, while FactoryGirl.find_definitions
reloads all definitions from file.
Be sure to use the factory_girl_rails
gem if your on Rails. When you've for example defined a factory :user
, you can use it in your console with FactoryGirl.build(:user)
or FactoryGirl.create(:user)
. This will return a User instance.
If that doesn't work, please post some more details.
回答2:
I was using Faker. See the diff of changes that solved the problem:
# factories/building.rb, address is a string
- address Faker::Address.street_address
+ address { Faker::Address.street_address }
# factories/user.rb, email is a string
- email Faker::Internet.email
+ email { Faker::Internet.email }
And then FactoryGirl.reload
works.
来源:https://stackoverflow.com/questions/12307091/reload-factory-girl-factory