【问题标题】:NameError: uninitialized constant FactoryNameError:未初始化的常量工厂
【发布时间】:2012-09-11 21:59:22
【问题描述】:

我正在关注this tutorial,开始与工厂女孩 rspec 一起在 Rails 上使用 TDD,但我遇到了这个问题,我无法理解。

这是我的“工厂”.rb (events.rb)

require 'faker'

FactoryGirl.define do
   factory :event do
     name "HIGH"
     genre "house, techno, idb"
     venue_name "Westbourne Studios"
     venue_address "4-6 Chamberlayne Road"
     venue_postcode "NW103JD"
     begin_time "10pm"
     end_time "2am"
     user_id 2
     description "A Super massive party with loads of everything you would want around."
     status true
     venue_id nil
   end
end

这里是 event_spec.rb:

require 'spec_helper'
require 'factory_girl_rails'

describe Event do

it "has a valid factory" do
  Factory.create(:event).should be_valid
end

  it "is invalid without a name"
  it "is invalid without a genre"
  it "is invalid without a venue_name"
  it "is invalid without a venue_address"
  it "is invalid without a venue_postcode"
  ...

 end

我已经设置了模型,迁移了等等。当我运行“rspec spec/models/event_spec.rb”时,我收到以下错误:

Failures:

1) Event has a valid factory
 Failure/Error: Factory.create(:event).should be_valid
 NameError:
   uninitialized constant Factory
 # ./spec/models/event_spec.rb:7:in `block (2 levels) in <top (required)>'

 Finished in 0.1682 seconds
 13 examples, 1 failure, 12 pending

 Failed examples:

 rspec ./spec/models/event_spec.rb:6 # Event has a valid factory

 Randomized with seed 64582

【问题讨论】:

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


    【解决方案1】:

    尝试以这种方式使用它:

    FactoryGirl.create(:event).should be_valid
    

    我想,我记得,它只是旧版本 gem 中的“工厂”。如果你看一下Factory Girl最近的"Getting started" guide,只有“FactoryGirl”的电话。

    【讨论】:

    • 我知道这会很愚蠢...非常感谢:)
    • Factory 在以前的版本中已被弃用,我认为它在当前版本中已被删除
    【解决方案2】:

    如果您创建文件 spec/support/factory_girl.rb 的内容:

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

    那么你可以简单地使用:

    create(:event)
    build(:book)
    

    代替:

    FactogyGirl.create(:event)
    FactogyGirl.build(:book)
    

    【讨论】:

      【解决方案3】:

      我在使用 factory bot 时遇到了同样的错误,为了补充 Stefan 的回答,我发现了这个小备忘单。

      https://devhints.io/factory_bot

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-19
        • 2015-10-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-04
        相关资源
        最近更新 更多