【问题标题】:RSpec factories with FactoryBot 'uninitialized constant FactoryBot'具有 FactoryBot '未初始化常量 FactoryBot' 的 RSpec 工厂
【发布时间】:2018-09-15 16:57:23
【问题描述】:

我正在按照this tutorial 设置请求规范。 如果我使用 bundle exec rspec 运行测试,我会收到以下错误:

An error occurred while loading ./spec/factories/entities_spec.rb.
Failure/Error:
  FactoryBot.define do
    factory :entity do
      name { FFaker::Lorem.word }
    end
  end

NameError:
  uninitialized constant FactoryBot

本教程只要求向 rails_helper.rb 文件添加一些配置。我不知道我需要在哪里添加require 'factory_bot'。如果我将它添加到 rails_helper.rb 文件的顶部,错误仍然存​​在。如果我将它添加到 factory/entity_spec.rb 文件中,我会收到此错误:

An error occurred while loading ./spec/requests/entities_spec.rb.
Failure/Error:
  factory :entity do
    name { FFaker::Lorem.word }
  end

FactoryBot::DuplicateDefinitionError:
  Factory already registered: entity

【问题讨论】:

  • 嗯,为什么你的spec文件中有工厂定义?
  • 它不在里面。因为然后 DuplicateDefinitionError 被抛出。
  • 我在ActionMailer::Preview 类中使用FactoryBot,该类位于development 环境中,而我的factory_bot_rails gem 仅在test 组中。所以我把它移到我们的小组test development

标签: ruby-on-rails rspec ruby-on-rails-5 factory-bot


【解决方案1】:

只需重命名我的 factories/*.rb 文件,例如factories/user_spec.rbfactories/user.rb 解决了这个问题。

【讨论】:

    猜你喜欢
    • 2021-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多