我在 Rails 4 中使用 Factory Girl 时遇到“工厂未注册”错误。这是我在 spec/factories/user.rb 中为简单的 Devise 用户定义的工厂:
FactoryGirl.define do
factory :user do
email 'test@example.com'
password 'foobar'
password_confirmation 'foobar'
end
end
这是 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
在 gem 文件中:
gem 'factory_girl_rails', :require => false
这是 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
这失败了,说“工厂未注册:用户”。我尝试将工厂定义移动到 spec/factories.rb,以及仅使用 factory_girl 而不是 factory_girl_rails,但没有成功。任何建议将不胜感激。