40

我一直在关注这个Rails 测试介绍,我遇到了一个我似乎找不到解决方案的问题。我非常熟悉 Rails,但这是我第一次尝试测试。

无论如何,我有一个非常基本的模型测试,甚至没有完全实现,当我尝试运行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

非常感谢您的帮助

宝石文件

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
4

4 回答 4

122

应该是FactoryGirl.create。显然Factory已被弃用,现在已被删除,请查看您提供的链接中的评论:)

于 2012-08-09T01:55:43.280 回答
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 文档

于 2014-02-09T18:03:55.380 回答
9

这不是您的问题的答案,但我注意到您在使用 Faker 和 FactoryGirl 时存在一个模糊的错误。对于每个 FactoryGirl.create 或 FactoryGirl.build,f.namef.email都是相同的。

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

在 Faker 调用周围添加花括号,这样每次对 Factory 的引用都会生成随机的 Faker 数据。

f.name { Faker::Name.name }
f.email { Faker::Internet.email }
于 2012-08-12T05:12:11.593 回答
1

此外,请确保您在 spec_helper.rb 文件中包含了 require 语句。

require 'factory_girl_rails'
于 2015-07-05T21:49:55.090 回答