2012-03-29 75 views
0

我想我在使用rails配置FactoryGirl時遇到問題。我最初遵循ASCIIcasts #275: how i test,但耙給我NameError: uninitialized constant ...如何正確設置和使用factory_girl_rails?

我錯過了什麼嗎?有可能某些配置文件是錯誤的嗎?我對RSpec和Rails很新。

我使用的Rails 3.2.2 + Mongoid + RSpec的 + factory_girl_rails

錯誤:

Failures: 

    1) User should save user with valid required fields 
    Failure/Error: let(:user) { FactoryGirl.build(:valid_user) } 
    NameError: 
     uninitialized constant ValidUser 
    # ./spec/models/user_spec.rb:4:in `block (2 levels) in <top (required)>' 
    # ./spec/models/user_spec.rb:7:in `block (2 levels) in <top (required)>' 

規格/ factories.rb

FactoryGirl.define do 
    factory :valid_user do 
    name  'somename' 
    email '[email protected]' 
    password 'somepassword' 
    end 
end 

規格/型號/ user_spec.rb

require 'spec_helper' 

describe User do 
    let(:user) { FactoryGirl.build(:valid_user) } 

    it "should save user with valid required fields" do 
    user.should be_valid 
    end 
end 

規格/ spec_helper.rb

ENV["RAILS_ENV"] ||= 'test' 
require File.expand_path("../../config/environment", __FILE__) 
require 'rspec/rails' 
require 'rspec/autorun' 
require 'capybara/rspec' 

Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f} 

RSpec.configure do |config| 
    config.infer_base_class_for_anonymous_controllers = false 

    config.include FactoryGirl::Syntax::Methods 
end 

回答

5

它通常是很有幫助的輸出整錯誤,或至少整個第一句話 - 你還沒有告訴我們缺少的常量是什麼!

更新:謝謝你的整個錯誤。當您定義工廠:valid_user時,Factory Girl將自動假定它是針對名爲ValidUser的型號。爲了解決這個問題,你可以命名你的工廠:user(假設你有一個User模型),或者你可以嘗試:

FactoryGirl.define do 
    factory :valid_user, :class => User do 
    name  'somename' 
    email '[email protected]' 
    password 'somepassword' 
    end 
end 

另外,如果你想有幾個不同類型的用戶工廠,你可以使用方法:

FactoryGirl.define do 
    factory :user do 
    # set some attrs 
    end 

    factory :valid_user, :parent => :user do 
    name  'somename' 
    email '[email protected]' 
    password 'somepassword' 
    end 

    factory :invalid_user, :parent => :user do 
    # some other attrs 
    end 
end 
+0

感謝您的回答。我添加了整個錯誤信息。顯然,'Factory.build'很快就會被棄用。 (拒絕警告:Factory.build已棄用;請改用FactoryGirl.build。) – 2012-03-29 15:39:26

+0

好的,我更新了我的答案。 – muffinista 2012-03-29 17:32:10

+0

哇,傻我!我應該想知道工廠女孩應該如何猜測模型!非常感謝。 – 2012-03-29 18:48:32

1

你可以聲明廠這樣........

Factory.define :organization do |g| 
    g.name 'Test Organization' 
    g.phone_number '5345234561' 
    g.website_url 'www.testorg.com' 
    g.city 'chichago ' 
    g.association :state 

end 

而在這樣的organization_spec使用它.....

require 'spec_helper' 

describe Organization do 
    before :each do 
    @state = Factory :state 
    @organization = Factory :organization ,:state => @state 
    end 

    it "should be invalid without a name" do 
    @organization.name = nil 
    @organization.should_not be_valid 
end 

end 

,享受!!!!!!!!!!!!!!!!

+0

我完全按照你所說的,但問題依然存在。 :(我認爲問題出在我的配置文件上,你能解釋我怎麼設置factory_girl_rails?我應該更改哪些配置文件? – 2012-03-29 15:56:28