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

问题描述 投票:0回答:6

如果我添加:

config.include FactoryBot::Syntax::Methods  

RSpec.configure do |config|  

并运行 rspec,我看到此错误:

/Users/perry_mac/rails_projects/mymri/spec/spec_helper.rb:21:在`块中 in ': 未初始化常量 FactoryBot (NameError)

我的gemfile.lock可以在这个pastebin
中看到 我的 gemfile 可以在 this Pastebin

中看到

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

注:FactoryBot 以前称为 FactoryGirl

ruby-on-rails rspec factory-bot rspec-rails
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
投票

还要确保

require 'factory_bot'
spec/support/factory_bot.rb

这最终成为我的问题。


4
投票

确保将

require 'support/factory_girl'
包含在
spec/rails_helper.rb
之后
require 'rspec/rails'

我将其放在

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. require 'support/factory_bot.rb'
    文件中添加
    spec/rails_helper.rb
    或取消注释
    rails_helper.rb
    中的以下行:
Dir[Rails.root.join('spec', 'support', '**', '*.rb')].sort.each { |f| require f }

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 的开发人员注意。

© www.soinside.com 2019 - 2024. All rights reserved.