30

我正在关注 Michal Hartls Rails 教程第 7 章。我已经安装了 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

宝石文件

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

我的 factory.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)

在我的第 10 行,user_controller_spec.rb因为我收到了贬值警告。我认为这会解决它,但现在我刚刚得到。

Factory not registered: user

有人可以告诉我发生了什么吗?

4

6 回答 6

54

我已经修好了。

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

于 2012-11-12T00:01:02.973 回答
41

当我在那一章中第一次使用 FactoryGirl 时,我遇到了同样的错误,如果你正在使用它,我需要做的就是重新启动服务器和 Spork。希望能帮助到你

于 2012-06-14T06:04:06.767 回答
6

如果你先定义工厂,而不是创建它呢?尝试这个:

FactoryGirl.define do
  factory :user do
    name                  "Mark Brown"
    email                 "mbrown@yahoo.com"
    password              "foobar"
    password_confirmation "foobar"
  end 
end
于 2012-05-07T14:35:39.783 回答
3

您将需要测试组下的 gem 'factory_girl_rails'

于 2012-05-16T21:07:54.163 回答
1

在你的 Gemfile 你应该用这个替换

gem "factory_girl_rails", "~> 4.0"

代替

gem "factory_girl", "~> 3.2.0"
于 2014-07-15T03:15:02.890 回答
1

我使用 pry 作为我的 IRB。当我从我的宝石中取出它时,我能够让工厂女孩正常使用。

rails c -e test

irb ->  FactoryGirl.create(:user)

也许有人可以解释如何使用 pry 来完成这项工作。

于 2017-07-17T11:45:36.480 回答