我正在尝试关注railstutorial.org,目前正在第7章开始使用工厂:http://railstutorial.org/chapters/modeling-and-viewing-users-two#sec:tests_with_factories
我正在使用Rails 3.0.1和ruby-1.9.2-p0
我不能为我的生活让我的rspec测试通过,我得到的错误是
Failures:
1) UsersController GET 'show' should be successful
Failure/Error: @user = Factory(:user)
undefined method `Factory' for #<RSpec::Core::ExampleGroup::Nested_2::Nested_1:0x00000101cc5608>
# ./spec/controllers/users_controller_spec.rb:9:in `block (3 levels) in <top (required)>'
my factories.rb看起来像这样:
# By using the symbol ':user', we get Factory Girl to simulate the User model.
Factory.define :user do |user|
user.name "Michael Hartl"
user.email "mhartl@example.com"
user.password "foobar"
user.password_confirmation "foobar"
end
这是我的users_controller_spec.rb
文件:
require 'spec_helper'
describe UsersController do
render_views
describe "GET 'show'" do
before(:each) do
@user = Factory(:user)
end
it "should be successful" do
get :show, :id => @user
response.should be_success
end
这是我的Gemfile,如果它有帮助:
source 'http://rubygems.org'
gem 'rails', '3.0.1'
# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'
gem 'sqlite3-ruby', :require => 'sqlite3'
gem 'gravatar_image_tag'
group :development do
gem 'rspec-rails'
gem 'annotate-models'
end
group :test do
gem 'rspec'
gem 'webrat'
gem 'spork'
gem 'factory_girl_rails'
end
答案 0 :(得分:21)
根据Factory Girl的最新版本(目前为v4.0.0) 重写factories.rb
FactoryGirl.define do
factory :user do
name "Michael Hartl"
email "mhartl@example.com"
password "foobar"
password_confirmation "foobar"
end
end
然后从用户控制器规范中将其命名为:
FactoryGirl.create(:user)
答案 1 :(得分:12)
我收到了完全相同的错误消息。我刚刚重启了我的Spork服务器和自动测试系统,一切都变得绿色了。
答案 2 :(得分:7)
也许你应该尝试新的语法(参见工厂女孩的github readme)
FactoryGirl.define :user do |user|
user.name "Michael Hartl"
user.email "mhartl@example.com"
user.password "foobar"
user.password_confirmation "foobar"
end
答案 3 :(得分:3)
在您的规范中使用
@user = FactoryGirl(:user)
而不是
@user = Factory(:user)
答案 4 :(得分:2)
我有这个问题,但这是因为我把工厂女孩宝石放在开发部分而不是Gemfile的测试部分。一旦进入测试部分,它就可以工作了。我在条目和你的条目之间注意到的一个区别是我的指定1.0:
group :test do
gem 'rspec-rails', '2.6.1'
gem 'webrat', '0.7.1'
gem 'factory_girl_rails', '1.0'
end
答案 5 :(得分:0)
对我来说,我必须将require 'factory_girl'
添加到test_helper.rb
答案 6 :(得分:0)
我的解决方案:我意外地将其包含在:development
区块中,只需将其移至:test
区块
(我在这里列出了它,因为它可能会帮助那些没有正确遵循教程的人)
答案 7 :(得分:0)
我这样做了,
将require 'factory_girl'
添加到test_helper.rb
和
@user = FactoryGirl.create(:user)
答案 8 :(得分:0)
对于那些现在找到这个页面的人:注意你曾经使用过“FactoryGirl”的地方,你现在必须在你的测试中使用“FactoryBot”。来自thinkbot公告页面:
“我们将factory_girl重命名为factory_bot(并将factory_girl_rails重命名为 factory_bot_rails)。现在,factory_girl的所有功能都相同 用不同的名字。“
此处有更多详情:
答案 9 :(得分:-1)
我决定使用最新版本的Factory Girl,所以我尝试调整代码。没有为我工作,所以我用
gem 'factory_girl_rails', '1.0'
在Gemfile中将版本锁定为1.0
bundle update
重新启动spork和autotest并且工作正常。