工厂未注册:用户

30

我正在按照Michal Hartls的Rails教程第七章进行学习。我已经安装了Factory girl gem。但是当我运行我的测试时,一直出现这个错误。

Failures:

 1) UsersController GET 'show' should be successful
     Failure/Error: @user = FactoryGirl.create(:user)
     ArgumentError:
       Factory not registered: user
     # ./spec/controllers/users_controller_spec.rb:10:in `block (3 levels) in <top (required)>'

Finished in 0.66336 seconds 42 examples, 1 failure

Failed examples:

rspec ./spec/controllers/users_controller_spec.rb:14 # UsersController GET 'show' should be successful
Gemfile
group :test do
  gem 'autotest', '4.4.6'
  gem "autotest-growl", "~> 0.2.16"
  gem "autotest-rails", "~> 4.1.2"
  gem "rspec", "~> 2.9.0"
  gem 'rspec-rails',  '2.9.0'
  gem 'webrat', '0.7.3'
  gem "spork",  '0.9.0'
  gem 'annotate', '~> 2.4.1.beta'
  gem "factory_girl", "~> 3.2.0"
end
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
gem 'therubyracer', :platform =>

我的user_controller_spec.rb文件是:

require 'spec_helper'

describe UsersController do

  render_views

  describe "GET 'show'" do
    before(:each) do
    @user = FactoryGirl.create(:user)
    end

    it "should be successful" do
      get :show, :id => @user
      response.should be_success
    end
  end

  describe "GET 'new'" do
    it "should be successful" do
      get :new
      response.should be_success
    end

    it "should have the right title" do
      get :new
      response.should have_selector('title', :content => "Sign up")
    end
  end
end

我的 factories.rb 文件是:

FactoryGirl.create :user do |user|
  user.name                   "Mark Brown"
  user.email                 "mbrown@yahoo.com"
  user.password               "foobar"
  user.password_confirmation  "foobar"
end

我进行了改变

Factory(:name)
FactoryGirl.create(:user)

在我的user_controller_spec.rb文件的第10行,因为我收到了一个弃用警告,所以我进行了修改。我本以为这样会解决问题,但现在我只是得到了:

Factory not registered: user

有人能告诉我正在发生什么吗?

6个回答

54

我已经解决了它。

解决方案是在我的Gemfile中将gem 'factory_girl'更改为gem 'factory_girl_rails'


41

当我第一次在那个章节使用FactoryGirl时,遇到了同样的错误,我只需要重新启动服务器和如果您正在使用它的话,Spork。希望这能帮助到您。


3
我也遇到同样的问题,重启Rails服务器、guard/spork后测试通过了。这有点烦人。 - Raj
Zeus用户的问题和解决方案相同。 - Pistos

6
如果你先定义工厂而不是创建它,会怎样呢?试试这个:
FactoryGirl.define do
  factory :user do
    name                  "Mark Brown"
    email                 "mbrown@yahoo.com"
    password              "foobar"
    password_confirmation "foobar"
  end 
end

3
您需要在测试组中使用gem 'factory_girl_rails'。

对我有用。我不小心使用了 gem 'factory_girl' 而不是 'factory_girl_rails'。 - Kyle Suss

1

我曾经在使用IRB时使用了pry。当我从我的gems中移除它后,我成功地使用了Factory girl。

rails c -e test

irb ->  FactoryGirl.create(:user)

也许有人能够解释如何使用pry使这个工作起来。

1
在你的Gemfile文件中,你应该使用以下代码替换:

gem "factory_girl_rails", "~> 4.0"

代替

gem "factory_girl", "~> 3.2.0"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接