如何将“config.include FactoryBot :: Syntax :: Methods”添加到spec_helper.rb中的rspec配置块中?

16

如果我添加:

config.include FactoryBot::Syntax::Methods  

以下

RSpec.configure do |config|  

当我运行rspec时,我看到这个错误:

/Users/perry_mac/rails_projects/mymri/spec/spec_helper.rb:21:in `block in ': uninitialized constant FactoryBot (NameError)

我的gemfile.lock可以在此 pastebin中查看。
我的gemfile可以在此 pastebin中查看。

如果我省略Rspec.configure语句,我的测试都能正常运行。我想使用缩写语法,但不确定我在这里做错了什么。

注意:FactoryBot以前被称为FactoryGirl。


1
Gemfile 中是否存在 gem 'factory_girl_rails' 这个 gem? - itsnikolay
1
在 rails_helper.rb 中出现了 require File.expand_path("../../config/environment", FILE)。 - Perry Horwich
你可以尝试使用我的 gem teleporter 进行 RSpec 的安装,然后运行 rails g initial:rspec_base,但在运行之前请提交你的更改。源代码在这里:https://github.com/itsNikolay/teleporter - itsnikolay
啊,什么?我不熟悉传送宝石。 - Perry Horwich
1
我很感激您的提供,但我希望能找到一个更具体的答案。谢谢。 - Perry Horwich
显示剩余4条评论
6个回答

16

懂了。

这个链接指引了我方向。

所需的修改应该在spec/support/factory_bot.rb进行,并且应该看起来像这样:

# RSpec
# spec/support/factory_bot.rb
RSpec.configure do |config|
  config.include FactoryBot::Syntax::Methods
end

注意:FactoryBot 以前被称为 FactoryGirl。


11

你必须把这个字符串添加到文件 'spec/RAILS_helper.rb' 中,而不是添加到 'spec_helper.rb' 文件中。


11

同时确保在 spec/support/factory_bot.rb 文件中添加 require 'factory_bot'

这就是最终导致问题的原因。


4
请确保在require 'rspec/rails'之后,在spec/rails_helper.rb中包含require 'support/factory_girl'。我曾经将它放在require 'spec_helper'之后,结果出现了错误。

3
这篇答案是基于之前的评论和 factory_bot 进行编写和测试的。
1. 创建 spec/support/factory_bot.rb 文件。 2. 将以下内容粘贴到 spec/support/factory_bot.rb 文件中:
require 'factory_bot'

RSpec.configure do |config|
  config.include FactoryBot::Syntax::Methods
end
  1. spec/rails_helper.rb文件中添加 require 'support/factory_bot.rb'
  2. 愉快地编写测试。

0
我认为在这里值得一提的是,如果使用FactoryGirl,您将收到一个弃用消息:
The factory_girl gem has been deprecated and has been replaced by factory_bot. Please switch to factory_bot as soon as possible.

提醒未来的开发人员,如果要使用FactoryGirl,请注意以下内容。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接