How do I use factories from FactoryGirl in rails console

耗尽温柔 提交于 2019-11-29 20:01:08
muttonlamb

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.

Alex Popov

I do this the following way:

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

    rails console 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.

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!