16

我正在按照本教程开始使用工厂女孩 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
4

3 回答 3

57

尝试以这种方式使用它:

FactoryGirl.create(:event).should be_valid

我想,我记得,它只是旧版本的 gem 中的“工厂”。如果您查看最近的 Factory Girl 的“入门”指南,则只有“FactoryGirl”的调用。

于 2012-09-11T22:07:18.430 回答
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)
于 2012-11-23T14:58:28.640 回答
2

我在使用工厂机器人时遇到了同样的错误,为了补充 Stefan 的回答,我遇到了这个小备忘单。

https://devhints.io/factory_bot

于 2017-11-08T06:22:02.913 回答