Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use factories from FactoryGirl in rails console

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 
like image 226
Eric Baldwin Avatar asked Aug 12 '13 20:08

Eric Baldwin


People also ask

What are factories in Ruby on Rails?

Factory method is a creational design pattern which solves the problem of creating product objects without specifying their concrete classes. The Factory Method defines a method, which should be used for creating objects instead of using a direct constructor call ( new operator).

What does factory bot do?

factory_bot is a fixtures replacement with a straightforward definition syntax, support for multiple build strategies (saved instances, unsaved instances, attribute hashes, and stubbed objects), and support for multiple factories for the same class (user, admin_user, and so on), including factory inheritance.


2 Answers

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.

like image 67
Alexander Popov Avatar answered Oct 09 '22 02:10

Alexander Popov


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.

like image 41
muttonlamb Avatar answered Oct 09 '22 04:10

muttonlamb