How do I use factories from FactoryGirl in rails console

后端 未结 3 466
无人及你
无人及你 2020-12-22 20:39

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\"

3条回答
  •  猫巷女王i
    2020-12-22 21:23

    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.

提交回复
热议问题