我认为我在使用rails配置FactoryGirl时遇到问题。我最初关注ASCIIcasts #275: how i test,但是rake正在给我NameError: uninitialized constant ...
我错过了什么吗?是否有可能某些配置文件错误?我是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 'a@b.com'
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
答案 0 :(得分:5)
输出整个错误或至少整个第一句通常很有帮助 - 你甚至没有告诉我们缺少的常数是什么!
更新:感谢整个错误。定义factory:valid_user时,Factory Girl将自动假定它适用于名为ValidUser
的模型。要解决此问题,您可以为工厂命名:user
(假设您有User
型号),或者您可以尝试:
FactoryGirl.define do
factory :valid_user, :class => User do
name 'somename'
email 'a@b.com'
password 'somepassword'
end
end
或者,如果您想拥有几种不同类型的用户工厂,可以使用:
FactoryGirl.define do
factory :user do
# set some attrs
end
factory :valid_user, :parent => :user do
name 'somename'
email 'a@b.com'
password 'somepassword'
end
factory :invalid_user, :parent => :user do
# some other attrs
end
end
答案 1 :(得分: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
享受!!!!!!!!!!!!!!!!