Rails 3.2,RSpec,Factory Girl:NameError:未初始化的常量Factory
我一直在跟随这个入门到Railstesting,我遇到了一个问题,我似乎无法find解决scheme。 我对Rails非常熟悉,但是这是我第一次进入testing阶段。
无论如何,我有一个非常基本的模型testing,甚至没有完全实现,当我尝试运行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
/spec/models/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
应该是FactoryGirl.create
。 显然Factory
已被弃用,现在已被删除,看你提供的链接中的意见:)
实际上在你spec_helper.rb
下的spec_helper.rb
下Rspec.configure do...end
你可以添加
RSpec.configure do |config| config.include FactoryGirl::Syntax::Methods end
这将为您节省前缀FactoryGirl.
的麻烦FactoryGirl.
之前:build
和:create
完全: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文档
这不是你的问题的答案,但我注意到,在FactoryGirl中使用Faker有一个模糊的错误。 每个FactoryGirl.create或FactoryGirl.build的f.name和f.email都是一样的。
f.name Faker::Name.name f.email Faker::Internet.email
在Faker调用中添加大括号,以便每个对Factory的引用都会生成随机的Faker数据。
f.name { Faker::Name.name } f.email { Faker::Internet.email }
此外,请确保您在spec_helper.rb文件中包含require语句。
require 'factory_girl_rails'