'Factory not registered' error in Rails 4

2019-08-30 02:46发布

问题:

I am getting a 'Factory not registered' error using Factory Girl in Rails 4. Here is my factory definition for a simple Devise user in spec/factories/user.rb:

FactoryGirl.define do
  factory :user do
    email 'test@example.com'
    password 'foobar'
    password_confirmation 'foobar'
  end
end

Here is the spec_helper.rb:

ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'email_spec'
require 'rspec/autorun'
require 'factory_girl'

Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }
ActiveRecord::Migration.check_pending! if defined?(ActiveRecord::Migration)

RSpec.configure do |config|

  config.include(EmailSpec::Helpers)
  config.include(EmailSpec::Matchers)
  config.fixture_path = "#{::Rails.root}/spec/fixtures"
  config.use_transactional_fixtures = true
  config.infer_base_class_for_anonymous_controllers = false
  config.order = "random"
  config.include Devise::TestHelpers, :type => :controller
  config.include FactoryGirl::Syntax::Methods
  config.before(:suite) do
    DatabaseCleaner.strategy = :truncation
  end
  config.before(:each) do
    DatabaseCleaner.start
  end
  config.after(:each) do
    DatabaseCleaner.clean
  end
end

And in the gem file:

gem 'factory_girl_rails', :require => false

And here is the test in spec/models/user_spec.rb:

require 'spec_helper'

describe User do
  it "has a valid factory" do
    FactoryGirl.build(:user).should be_valid
  end
end

This fails, saying 'Factory not registered: user'. I've tried moving the Factory definition to spec/factories.rb, as well as using just factory_girl instead of factory_girl_rails, with no luck. Any suggestions would be greatly appreciated.

回答1:

You're requiring factory_girl instead of factory_girl_rails. Edit the equivalent line in your spec_helper.rb to this:

require 'factory_girl_rails'