Ruby Gem:未初始化的常量FactoryBot

Bry*_* L. 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
Run Code Online (Sandbox Code Playgroud)

并在spec_helper.rb:

require 'support/factory_bot'
Run Code Online (Sandbox Code Playgroud)

当我尝试运行spec rake任务时,我收到此错误:

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

我错过了什么?当我使用旧的factory_girl gem时,这常常工作正常,但它已经打破了重命名为factory_bot.谢谢!!

Bry*_* L. 22

卫生署.愚蠢的错误在这里,运行bundle exec rake spec而不是rake spec解决它.

也不得不添加require 'factory_bot'到顶部support/factory_bot.rb

  • 只需添加"require"factory_bot'即可. (16认同)

d1j*_*i1b 18

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

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

RSPEC在rails项目中初始化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
Run Code Online (Sandbox Code Playgroud)

添加参考 spec/rails_helper.rb

require 'support/factory_bot'
Run Code Online (Sandbox Code Playgroud)

以及删除任何fixture未使用的引用,如此 config.use_transactional_fixtures = true

应该是它!,最后spec在rspec默认文件夹中运行你想要的任何文件,例如: 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安装过程的人