Ruby-on-rails 如何在 rails 控制台中使用 FactoryGirl 的工厂
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18195851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I use factories from FactoryGirl in rails console
提问by Eric Baldwin
I am using rails console in the development environment and I want to use factories. How can I get access to them?
我在开发环境中使用 rails 控制台,我想使用工厂。我如何才能访问它们?
I have tried require "FactoryGirl"which returns
我试过require "FactoryGirl"哪个返回
1.9.3p393 :301 > require "FactoryGirl"
LoadError: cannot load such file -- FactoryGirl
采纳答案by muttonlamb
To solve this problem ensure that the factory bot gem is specifed in your Gemfile similar to this
要解决此问题,请确保在您的 Gemfile 中指定了与此类似的 factory bot gem
group :development, :test do
gem 'factory_bot_rails'
end
Then bundle install.
然后bundle install。
This should make FactoryBot class available in the development console.
这应该使 FactoryBot 类在开发控制台中可用。
Hope this helps.
希望这可以帮助。
回答by Alexander
I do this the following way:
我按以下方式执行此操作:
Start the rails console in test environment in sandbox mode.
rails console -e test --sandbox
以沙盒模式在测试环境中启动 rails 控制台。
rails console -e test --sandbox
You need this for two reasons:
你需要这个有两个原因:
- Any changes you do are rolled back.
- 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.
- 您所做的任何更改都会回滚。
- 如果您已经有一些种子数据,工厂可能会从 1 开始序列化属性,但这些记录可能已经存在。
Then in the console:
然后在控制台中:
Require FactoryBot (was called FactoryGirl):
require 'factory_bot'Load the factory definitions:
FactoryBot.find_definitionsInclude the FactoryBot methods to avoid prefixing all calls to FB with
FactoryBot(createinstead ofFactoryBot.create):include FactoryBot::Syntax::Methods
需要 FactoryBot(被称为 FactoryGirl):
require 'factory_bot'加载工厂定义:
FactoryBot.find_definitions包括 FactoryBot 方法,以避免在对 FB 的所有调用之前使用
FactoryBot(create而不是FactoryBot.create):include FactoryBot::Syntax::Methods
P.S. For fabrication gemyou can load the definitions in the rails console with:
PS 对于制造 gem,您可以使用以下命令在 rails 控制台中加载定义:
Fabrication.manager.load_definitions
Also require 'faker'if you use it.
require 'faker'如果你使用它也是如此。
回答by Robin Daugherty
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 FactoryBotavailable.
您需要require 'factory_bot_rails',这是 Rails 正在使用的实际 gem。该 gem 将包括 Factory Bot 库,FactoryBot可供使用。
You can either do this, or update your Gemfile to require it at startup as in muttonlamb's answer.
您可以这样做,也可以更新您的 Gemfile 以在启动时要求它,如 muttonlamb 的回答。

