2012-03-29 74 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