Ruby Gem: 未初始化的常量FactoryBot

32

我正在开发一个 Ruby gem 并尝试在其中使用 RSpec 和 FactoryBot。

support/factory_bot.rb 文件中,我有以下内容:

RSpec.configure do |config|
  config.include FactoryBot::Syntax::Methods

  config.before(:suite) do
    FactoryBot.find_definitions
  end
end

同时,在spec_helper.rb文件中:

require 'support/factory_bot'

当我尝试运行spec rake任务时,会出现此错误:

support/factory_bot.rb:2:in `block in <top (required)>': uninitialized constant FactoryBot (NameError)

我错过了什么?在我使用旧的factory_girl宝石时,这个功能运行良好,但是在改名为factory_bot后就崩溃了。谢谢!


我不确定你是否真的需要 "config.before(:suite) do" 这部分。 - Joseworks
5个回答

44

这里犯了一个愚蠢的错误,运行rake spec而不是bundle exec rake spec就解决了。

还需要在support/factory_bot.rb的顶部添加require 'factory_bot'


29

如果您是从头开始操作,请查看概述

安装细节 在这里 (基本上是添加gemGemfile,然后运行bundle install)

在您的Rails项目中初始化RSPECrails g rspec:install

创建新文件spec/support/factory_bot.rb并添加以下基本代码:

require 'factory_bot'

RSpec.configure do |config|
    config.include FactoryBot::Syntax::Methods
end

# RSpec without Rails
RSpec.configure do |config|
    config.include FactoryBot::Syntax::Methods

    config.before(:suite) do
        FactoryBot.find_definitions
    end
end

spec/rails_helper.rb 中添加引用

require 'support/factory_bot'

还有要做的,就是移除任何未使用的fixture引用,比如这个:config.use_transactional_fixtures = true

就这样了!最后在rspec默认文件夹内运行任何您想要的spec文件 例如: spec/features/my_action_spec.rb

spec/models/my_model_spec.rb

spec/task/my_task_spec.rb

或者一次性运行它们并检查取决于您的设置

rspec

rails rspec

bundle exec rspec

希望这可以帮助一些人进行整个RSPEC+FactoryBotGem安装过程。


我所需做的就是在 rails_helper.rb 中添加 require 'factory_bot'。 - Daniel Viglione

4

我也遇到过这个问题,移除

require 'support/factory_bot'

在rails_helper中有一行代码,只需将其取消注释:

Dir[Rails.root.join('spec', 'support', '**', '*.rb')].sort.each { |f| require f }

0
在我的情况下,我必须将以下行放置在文件spec/rails_helper.rb的'require "rspec/rails"'下面:
例如:
require "rspec/rails"
require_relative "support/factory_bot"
require_relative "support/chrome"

0
我曾经遇到过类似的问题。我通过移除默认的测试套件(MiniTest)来解决它。当您创建一个Rails应用程序并打算使用rspec和factory_bot时,请在命令行中使用以下代码:
rails new myapp -T
希望这可以帮助您。

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