railstutorial.org – 未定义的方法`工厂’

我正在尝试关注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 # # ./spec/controllers/users_controller_spec.rb:9:in `block (3 levels) in ' 

我的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 

也许你应该尝试新的语法(参见工厂女孩的github自述文件 )

 FactoryGirl.define :user do |user| user.name "Michael Hartl" user.email "mhartl@example.com" user.password "foobar" user.password_confirmation "foobar" end 

根据最新版本的Factory Girl(目前为v4.0.0)重写factory.rb

 FactoryGirl.define do factory :user do name "Michael Hartl" email "mhartl@example.com" password "foobar" password_confirmation "foobar" end end 

然后从用户控制器规范中调用它:

 FactoryGirl.create(:user) 

我得到了完全相同的错误消息。 我刚刚重新启动了我的Spork服务器和自动测试,一切都变成了绿色。

在您的规范中使用

  @user = FactoryGirl(:user) 

代替

  @user = Factory(:user) 

我有这个问题,但这是因为我把工厂女孩gem放在开发部分而不是Gemfile的测试部分。 一旦进入测试部分,它就可以工作了。 我和我的条目之间的一个区别是我的指定1.0:

 group :test do gem 'rspec-rails', '2.6.1' gem 'webrat', '0.7.1' gem 'factory_girl_rails', '1.0' end 

对我来说,我必须将require 'factory_girl'添加到test_helper.rb

我的解决方案:我不小心将它包含在:development块中,只需将其移动到:test

(我在这里列出了它,因为它可能会帮助那些没有正确遵循教程的人)

我已经这样做了,将require 'factory_girl'添加到test_helper.rb

 @user = FactoryGirl.create(:user) 

对于那些现在找到这个页面的人:注意你曾经使用过“FactoryGirl”的地方,你现在必须在测试中使用“FactoryBot”。 从思想机器人公告页面:

“我们将factory_girl重命名为factory_bot(并将factory_girl_rails重命名为factory_bot_rails)。所有相同的factory_girlfunction,现在名称不同。”

更多细节在这里:

https://robots.thoughtbot.com/factory_bot

我决定使用最新版本的Factory Girl,所以我尝试调整代码。 不适合我,所以我用过

 gem 'factory_girl_rails', '1.0' 

在Gemfile中将版本锁定为1.0

 bundle update 

重新启动spork和autotest,它工作。