How do I use factories from FactoryGirl in rails console

Ruby on-RailsFactory Bot

Ruby on-Rails Problem Overview


I am using rails console in the development environment and I want to use factories. How can I get access to them?

I have tried require "FactoryGirl" which returns

1.9.3p393 :301 > require "FactoryGirl"
LoadError: cannot load such file -- FactoryGirl

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

I do this the following way:

  • Start the rails console in test environment in sandbox mode.

      rails console -e test --sandbox
    

You need this for two reasons:

  1. Any changes you do are rolled back.
  2. If you already have some seed data it might happen that the factories will start the serialization of attributes from 1, but these records might already exist.

Then in the console:

  • Require FactoryBot (was called FactoryGirl):

      require 'factory_bot'
    
  • Load the factory definitions:

      FactoryBot.find_definitions
    
  • Include the FactoryBot methods to avoid prefixing all calls to FB with FactoryBot (create instead of FactoryBot.create):

      include FactoryBot::Syntax::Methods
    

P.S. For fabrication gem you can load the definitions in the rails console with:

Fabrication.manager.load_definitions

Also require 'faker' if you use it.

Solution 2 - Ruby on-Rails

To solve this problem ensure that the factory bot gem is specifed in your Gemfile similar to this

group :development, :test do
  gem 'factory_bot_rails'
end

Then bundle install.

This should make FactoryBot class available in the development console.

Hope this helps.

Solution 3 - Ruby on-Rails

You need to require 'factory_bot_rails', which is the actual gem that's being used by Rails. That gem will include the Factory Bot library, making FactoryBot available.

You can either do this, or update your Gemfile to require it at startup as in muttonlamb's answer.

Solution 4 - Ruby on-Rails

If you want to have it available each time you start the console, you can add this piece of code to the top of your config/environments/development.rb:

require 'factory_bot_rails'
require 'faker' # if you're also using faker gem
require 'rails/console/helpers'
Rails::ConsoleMethods.prepend(FactoryBot::Syntax::Methods)

Now you can use the built-in helpers right after starting the console, for example:

company = create(:company)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEric BaldwinView Question on Stackoverflow
Solution 1 - Ruby on-RailsAlexander PopovView Answer on Stackoverflow
Solution 2 - Ruby on-RailsmuttonlambView Answer on Stackoverflow
Solution 3 - Ruby on-RailsRobin DaughertyView Answer on Stackoverflow
Solution 4 - Ruby on-RailsJackaView Answer on Stackoverflow