【问题标题】:Factory Girl: NameError unintialized constant for one of the factoriesFactory Girl:其中一个工厂的 NameError 未初始化常量
【发布时间】:2013-07-29 19:21:12
【问题描述】:

所以我有一个奇怪的问题,我声明了 3 个工厂,其中只有 1 个工厂被初始化,其余的都给未初始化常量。 我不知道我做错了什么。 我知道这个问题已经被问过很多次了,但没有一个答案能解决我的问题。

这是我的规范/工厂/sample_factory.rb

require 'faker'

FactoryGirl.define do

 factory :early_access do
     email {Faker::Internet.email}
 end

factory :login do
    email {Faker::Internet.email}
    password "password"
end

factory :user do
        display_name {Faker::Internet.name}
        email {Faker::Internet.email}
        username {Faker::Internet.username}
        password "password"
end

这是模型规格文件 spec/models/sample.rb

require 'spec_helper.rb'

describe EarlyAccess do

    it "has a valid factory" do
        FactoryGirl.build(:early_access).should be_valid
    end

    it "has a valid factory login" do
        FactoryGirl.build(:login).should be_valid
    end
end


    it "has valid factory user" do
        FactoryGirl.build(:user).should be_valid
    end
end

其中,只有第一个 early_access 通过,其余失败

.FF

Failures:

  1) EarlyAccess has a valid factory 2
     Failure/Error: FactoryGirl.build(:login).should be_valid
     NameError:
       uninitialized constant Login
     # ./spec/models/sample.rb:10:in `block (2 levels) in <top (required)>'

  2) EarlyAccess has valid factory user
     Failure/Error: 
     NameError:
       uninitialized constant User
     # ./spec/models/sample.rb:16:in `block (2 levels) in <top (required)>'

我已将 factory_girl_rails 包含在我的 spec_helper 中。

【问题讨论】:

  • 您有模型登录名和用户名吗?它尝试根据工厂名称初始化模型。如果工厂名称是用户,它会尝试做User.new
  • 我认为这与您的问题无关,但您的规范列表中有语法错误。第三个it 调用没有被describe 包围。

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


【解决方案1】:
  1. 确保您拥有 EarlyAccess、Login、用户定义的模型
  2. 模型应事先手动要求或符合 ActiveSupport::Dependencies 自动加载器约定(如分别位于 app/models/login.rb app/models/user.rb 中)。

如果这些模型位于某个非标准目录中 - 手动要求它们或将目录添加到 config/application.rb config.autoload_paths 数组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-19
    • 2015-10-29
    相关资源
    最近更新 更多