NameError:未初始化的常量工厂

时间:2012-09-11 21:59:22

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

我跟随this tutorial开始使用工厂女孩的轨道上的TDD,rspec,我遇到了这个问题我无法理解。

这是我的"工厂" .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

3 个答案:

答案 0 :(得分:56)

尝试以这种方式使用它:

FactoryGirl.create(:event).should be_valid

我想,我记得,在旧版本的宝石中它只是“工厂”。如果你看看最近的"Getting started" guide工厂女孩,只有“FactoryGirl”的电话。

答案 1 :(得分:9)

如果您使用内容创建文件规范/ support / factory_girl.rb:

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

然后你可以简单地使用:

create(:event)
build(:book)

而不是:

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

答案 2 :(得分:2)

我和工厂机器人有同样的错误,为了补充Stefan的答案,我偶然发现了这个小作弊表。

https://devhints.io/factory_bot