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\"
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:
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_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.
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.