'Factory not registered' error in Rails 4

拥有回忆 提交于 2019-12-13 07:36:26

问题


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'


来源:https://stackoverflow.com/questions/18690351/factory-not-registered-error-in-rails-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!