How to Quickly Troubleshoot FactoryGirl Factories?
Let’s say you are using FactoryGirl and you have run into some kind of a problem with it. You are lost and wondering what the quickest way to troubleshoot the problem is. Where to even start? Luckily for you, Toptal’s best Ruby on Rails developers are here to help provide you a hint and a path to solution. Let’s start then.
First, you need to try FactoryGirl in Rails console. Run your Rails console in test environment with
$ RAILS_ENV=test rails c --sandbox
If you have Rails 4 and above, use the following command:
$ rails c -e test --sandbox
Loading test environment in sandbox (Rails 4.2.1)
Any modifications you make will be rolled back on exit
As you can see from the welcome message above,
--sandbox option will roll all database changes back after you close the console. You didn’t intend to leave all the test data in the database created by your factories, did you?
After that, you need to require
factory_girl_rails, if it isn’t required automatically, in your test
# => true
Now you can create your models via FactoryGirl:
user = FactoryGirl.create(:user)
# lots of sql here
encrypted_password: "some password over here",
created_at: Fri, 13 Nov 2015 16:06:20 UTC +00:00,
updated_at: Fri, 13 Nov 2015 16:06:20 UTC +00:00,
name: "Karli Erdman Sr.",
authentication_token: "and maybe even some token",
If everything went smoothly, you should see in your SQL log all models have been saved correctly, and you will get your fresh user as a result from FactoryGirl. In case there is a problem, you’ll hopefully get an error message, or you’ll be able to understand more about your problem from the SQL log and what went wrong.