名称错误:未初始化的常量Factory。

17

我正在遵循这个教程,使用factory girl、rspec和rails进行TDD,但是我碰到了一个问题,我无法理解。

这是我的"factory".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个回答

57

尝试以这种方式使用它:

FactoryGirl.create(:event).should be_valid

我记得在旧版本的gem中只有"Factory"。如果你查看最近的"入门指南",你会发现只有使用"FactoryGirl"的调用。


1
我知道这一定是些愚蠢的事情...非常感谢 :) - Theo Felippe
2
“Factory”在之前的版本中已被弃用,我认为它在当前版本中已被移除。 - luacassus

10

如果您创建文件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)

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接