Ruby Gem:未初始化的常量FactoryBot

时间:2018-01-04 08:44:18

标签: ruby factory-bot

使用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 gem时,这常常工作正常,但它已经打破了重命名为factory_bot。谢谢!

4 个答案:

答案 0 :(得分:17)

卫生署。愚蠢的错误,运行bundle exec rake spec而不是rake spec解决了它。

还必须将require 'factory_bot'添加到support/factory_bot.rb

的顶部

答案 1 :(得分:17)

概述以防您从头开始这样做

安装rspec详细信息here(基本上将gem添加到Gemfile,然后运行bundle install

在您的rails项目RSPEC

中初始化rails 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 + FactoryBot Gem安装过程的人

答案 2 :(得分:0)

就我而言,require 'factory_bot'对我不起作用,运行spring stop,没关系。 MacOS版本:10.12.3

答案 3 :(得分:0)

我遇到过类似的问题。我通过删除默认测试套件( MiniTest )来解决它。当您创建 rails 应用程序并打算使用 rspec 和 factory_bot 时,请在命令行中使用以下代码:

rails new myapp -T

希望这对 xP 有所帮助

相关问题