ArgumentError:工厂未注册

时间:2014-05-25 00:38:26

标签: ruby-on-rails ruby rspec factory-bot

我正在尝试使用FactoryGirl运行rspec,但我一直收到此错误

1) Products Update with invalid information
     Failure/Error: let(:product) { FactoryGirl.create(:product) }
     ArgumentError:
       Factory not registered: product
     # ./spec/requests/products_spec.rb:47:in `block (3 levels) in <top (required)>'
     # ./spec/requests/products_spec.rb:52:in `block (3 levels) in <top (required)>'

-

这是带错误的测试(spec / requests / products_spec.rb):

describe "Read" do
    let(:product) { FactoryGirl.create(:product) }
    before { visit product_path(product) }
    it { should have_text(product.title) }
end

-

这是工厂(spec / factories.rb):

FactoryGirl.define do
    factory :product do
        title "Lorem ipsum"
        description "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce vitae ipsum consectetur, semper dolor sed, dignissim enim."
        image_url "lorem.png"
        price 9.95
    end
end

-

重新启动服务器(使用Spork和Guard)并没有任何改变,但我可能没有正确地重启Spork / Guard。

-

在我的spec / spec_helper.rb中确实需要'factory_girl'。

-

这是我的 Gemfile 。请注意我在我的Gemfile中使用“factory_girl_rails”

source 'https://rubygems.org'

gem 'rails', '4.1.1'
gem 'sass-rails', '~> 4.0.3'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.0.0'
gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder', '~> 2.0'
# gem 'bcrypt', '~> 3.1.7'

group :development do
    gem 'spring'
  gem 'sqlite3', '1.3.8'
  gem 'minitest'
  gem 'rspec-rails', '2.13.1'
  gem 'guard-rspec', '2.5.0'
  gem 'spork-rails', '4.0.0'
  gem 'guard-spork', '1.5.0'
end

group :test do
    gem 'selenium-webdriver', '2.35.1'
  gem 'capybara', '2.1.0'
  gem 'growl', '1.0.3'
  gem 'factory_girl_rails', '4.2.1'
end

group :production do
  gem 'pg', '0.15.1'
  gem 'rails_12factor', '0.0.2'
end

group :doc do
  gem 'sdoc', '0.4.0', require: false
end

-

你能找到错误吗?

2 个答案:

答案 0 :(得分:13)

我在这上面扔了很多东西,所以很难说出准确的解决方法是什么。我做的一件事是将spec_helper.rb中的require 'factory_girl'切换为require 'factory_girl_rails',这似乎是最合理的解决方案。

另外,我将config.include FactoryGirl::Syntax::Methods添加到了spec_helper.rb的Rspec.configure块中,我认为这也很重要。

答案 1 :(得分:0)

&#34; ArgumentError:工厂未注册&#34;如果您的工厂定义名称错误,也会生成。您的工厂定义可能被称为phases.rb,但定义应为:factory :phase do(单数)。