我正在开发环境中使用Rails控制台,想要使用工厂。我该如何访问它们?
我尝试了require "FactoryBot"
,但返回了错误信息。
1.9.3p393 :301 > require "FactoryBot"
LoadError: cannot load such file -- FactoryBot
我正在开发环境中使用Rails控制台,想要使用工厂。我该如何访问它们?
我尝试了require "FactoryBot"
,但返回了错误信息。
1.9.3p393 :301 > require "FactoryBot"
LoadError: cannot load such file -- FactoryBot
我是这样做的:
在沙盒模式下启动测试环境中的Rails控制台。
rails console -e test --sandbox
你需要这样做有两个原因:
然后在控制台中:
要求使用FactoryBot(之前称为FactoryGirl):
require 'factory_bot'
加载工厂定义:
FactoryBot.find_definitions
引入FactoryBot方法以避免在所有对FB的调用前加上前缀FactoryBot
(使用create
代替FactoryBot.create
):
include FactoryBot::Syntax::Methods
附注:对于fabrication gem,您可以使用以下命令在Rails console中加载定义:
Fabrication.manager.load_definitions
如果您使用它,还需要require 'faker'
。
fixture_file_upload
”的问题,这是由于缺少“ActionDispatch::TestProcess”模块引起的,因此您可能需要考虑将其包含在内。 - divideByZerorequire "factory_bot_rails"; include FactoryBot::Syntax::Methods; require 'ffaker'
- Mirror318rails console test
或rails console test --sandbox
即可。如果您不喜欢使用FactoryBot
前缀,请包含语法方法。 - Francisco Quinterorails c -e test --sandbox
。 - David Moralesgroup :development, :test do
gem 'factory_bot_rails'
end
bundle install
命令。gem 'factory_girl_rails',:require => false
,会导致任何试图从头开始设置开发环境的人遇到错误,请注意。 - Epigenerails console test
,它可以让你在测试环境中创建一个控制台,这样就不需要更新Gemfile来使用开发环境中的测试包。 - Dylan Pierce您需要导入'factory_bot_rails'
,这是Rails实际使用的Gem。该Gem将包含Factory Bot库,从而可用FactoryBot
。
您可以采取以下两种方法之一,要么执行此操作,要么像muttonlamb的答案那样在启动时更新您的Gemfile。
require 'factory_bot_rails'
require 'faker' # if you're also using faker gem
require 'rails/console/helpers'
Rails::ConsoleMethods.prepend(FactoryBot::Syntax::Methods)
现在您可以在启动控制台后立即使用内置帮助程序,例如:
company = create(:company)
Rails::ConsoleMethods.prepend(FactoryBot::Syntax::Methods)
(而不是之前的三个require
)就可以让它工作了(我不使用faker
)。 - Ed Ruderdevelopment
组中有这些gem,那么你是正确的 - 它们应该自动被要求。 - Jacka
rails c
然后执行require 'factory_bot'
。 - RudyOnRails