2012-08-09 49 views
40

我一直在跟隨this入門到Rails測試和我遇到了一個問題,我似乎找不到解決方案。我對Rails非常熟悉,但這是我第一次進行測試。Rails 3.2,RSpec,工廠女孩:NameError:未初始化的常量工廠

無論如何,我有一個非常基本的模型測試,甚至沒有完全實施,當我嘗試和運行rspec spec/models/admin_spec.rb。我得到的Admin has a valid factory線(全下面的代碼)以下錯誤

Admin has a valid factory 
Failure/Error: Factory.create(:admin).should be_valid 
NameError: 
    uninitialized constant Factory 
# ./spec/models/admin_spec.rb:6:in `block (2 levels) in <top (required)>' 

我認爲FactoryGirl心不是被加載由於某種原因,但我的印象是它應該會自動加載下。下面是從我的Gemfile,/spec/models/admin_spec.rb完整的代碼和/spec/factories/admins.rb

非常感謝您的幫助

的Gemfile

source 'https://rubygems.org' 

gem 'rails', '3.2.2' 
gem 'mysql2' 
gem 'jquery-rails' 
gem 'haml' 
gem 'bcrypt-ruby', :require => 'bcrypt' 
gem 'bootstrap-sass', '~> 2.0.2' 
gem 'capistrano' 
gem 'json' 
gem "paperclip", '~>3.0' 
gem 'airbrake' 
gem 'acts_as_list' 
gem 'nested_form', :git => 'https://github.com/ryanb/nested_form.git' 
gem 'bootstrap-wysihtml5-rails' 
gem 'will_paginate', '~> 3.0' 
gem 'bootstrap-will_paginate' 
gem 'thinking-sphinx', '2.0.10' 

gem 'sass-rails', '~> 3.1' 
gem 'coffee-rails' 
gem 'uglifier' 
# gem 'compass' 

group :development do 
    gem 'awesome_print' 
    gem 'wirble' 
end 

group :development, :test do 
    gem 'rspec-rails' 
    gem 'factory_girl_rails' 
end 

group :production do 
    gem 'execjs' 
    gem 'therubyracer' 
end 

group :test do 
    # Pretty printed test output 
    gem 'turn', :require => false 
    gem 'faker' 
    gem 'capybara' 
    gem 'guard-rspec' 
    gem 'launchy' 
end 

/spec/factories/admin.rb

require 'faker' 

FactoryGirl.define do 
    factory :admin do |f| 
    f.name Faker::Name.name 
    f.email Faker::Internet.email 
    end 
end 

/規格/月德爾斯/ admin_spec.rb

require 'spec_helper' 

describe Admin do 
    it "has a valid factory" do 
    Factory.create(:admin).should be_valid 
    end 
    it "is invalid without a name" 
    it "is invalid without an email" 
end 

回答

122

應該FactoryGirl.create代替。顯然Factory已被棄用,現在已被刪除,看看你提供的鏈接中的評論:)

+0

ahhh * sigh *。哈哈,非常感謝。我在頁面上找到了「未初始化的常量出廠錯誤」,但沒有足夠接近。我覺得這很簡單。再次感謝。 – chrisgooley 2012-08-09 02:02:52

9

這不是你的問題的答案,但我注意到有一個模糊的錯誤,在與FactoryGirl使用Faker 。 f.namef.email對於每個FactoryGirl.create或FactoryGirl.build都是相同的。

f.name Faker::Name.name 
f.email Faker::Internet.email 

在Faker調用中添加大括號,以便每個對Factory的引用都會生成隨機的Faker數據。

f.name { Faker::Name.name } 
f.email { Faker::Internet.email } 
+0

啊,我以後在檢查我的代碼的時候確實記得那個,但是無論如何感謝你們。 – chrisgooley 2012-08-13 06:13:38

+0

謝謝!愚蠢的錯誤,但容易錯過 – rpearce 2013-11-26 20:11:05

10

其實在你spec_helper.rbRspec.configure do...end您可以添加

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

這將節省您的前綴FactoryGirl.的麻煩:build:create乾脆之前:

需要 'spec_helper'

describe Admin do 
    it "has a valid factory" do 
    create(:admin).should be_valid 
    end 
    it "is invalid without a name" 
    it "is invalid without an email" 
end 

請參閱:FactoryGirl Documentation

1

此外,請確保您在spec_helper.rb文件中包含require語句。

require 'factory_girl_rails'