ArgumentError:工厂未注册

我试图让工厂女孩在我的rails 4.1.1应用程序中使用rspec运行。

问题是当我在命令行中运行rspec时,我得到Failure/Error: verse = build(:verse) ArgumentError: Factory not registered: verse

我很茫然,因为我检查了工厂女孩入门页面,这里有许多答案,我仍然无法解决这个问题。

在我的Gemfile中:

 gem 'rails', '4.1.1' group :development, :test do gem 'rspec-rails' gem "factory_girl_rails" end 

我的spec_helper.rb文件:

 require 'factory_girl_rails' RSpec.configure do |config| config.include FactoryGirl::Syntax::Methods end 

规格/控制器/ API / verses_controller_spec.rb

 describe "API Controller" do describe "show a verse" do it "should return status 200" do verse = build(:verse) get :show, id: verse.id expect(response).to have_http_status(200) end it "should return json object" do verse = build(:verse) get :show, id: verse.id JSON.parse(response.body).should == {'id' => verse.id} end end end 

规格/工厂/ verses.rb

 FactoryGirl.define do factory :verse do line1 "A beautiful verse I stand" end end 

为什么我的工厂没有正确装载? spec / factories文件夹中的文件应该自动加载。

使用带弹簧的rspec / factory girl时似乎存在问题。

添加:

 config.before(:all) do FactoryGirl.reload end 

在我的spec_helper.rb中解决了这个问题。

图片来源: https : //github.com/rails/spring/issues/88

编辑:

解决问题的另一种方法是手动告诉Factory Girl在哪里加载工厂。 在spec_helper中添加:

 FactoryGirl.definition_file_paths = [File.expand_path('../factories', __FILE__)] FactoryGirl.find_definitions 

这似乎是Factory Bot的一个问题 。 我用FactoryBot.find_definitions修复了它(根据问题报告):

 RSpec.configure do |config| config.include FactoryBot::Syntax::Methods config.before do FactoryBot.find_definitions end end 

这不一定是由Spring引起的。 有一个问题意味着factory_girl加载的路径与rspec略有不同。 解决方案是将以下内容添加到rails_helper中

 FactoryGirl.definition_file_paths << File.join(File.dirname(__FILE__), 'factories') FactoryGirl.find_definitions 

假设帮助程序处于engine_root / spec。

在rails引擎中使用rspec时会发生这种情况。