RSpec找不到Factorygirl的Factorys

时间:2010-11-29 11:35:47

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

我将在我的Rails3项目中使用RSpec和Factory girl。我已经安装了工厂女孩,但它没有找到我有这个错误的因素

Failure/Error: Factory.build(:user).should_be valid
No such factory: user

spec / factories / user_factory.rb:

Factory.define :user do |u|
  u.username 'otto'
end

规格/ spec_helper.rb

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

Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}

RSpec.configure do |config|
  config.mock_with :rspec
  config.fixture_path = "#{::Rails.root}/spec/fixtures"
  config.use_transactional_fixtures = true
end

的Gemfile:

group :development, :test do
   gem 'webrat'
   gem "cucumber-rails"
   gem "rspec-rails"
   gem "rspec"
   gem "autotest"
   gem 'factory_girl'
end

由于

4 个答案:

答案 0 :(得分:10)

您的config\application.rb

中是否有以下几行?
# Configure generators values.
config.generators do |g|
  g.test_framework  :rspec, :fixture => true
  g.fixture_replacement :factory_girl, :dir=>"spec/factories"
end

答案 1 :(得分:5)

将'factory_girl_rails'gem添加到您的:test,:开发组下的Gemfile中,如下所示:

group :development, :test do
   gem 'webrat'
   gem "cucumber-rails"
   gem "rspec-rails"
   gem "rspec"
   gem "autotest"
   gem 'factory_girl'
   gem 'factory_girl_rails'
end

在Rails 3中,您需要添加该gem才能使其正常工作。希望它有所帮助。

答案 2 :(得分:2)

您是否尝试过添加类似

的内容
Dir[Rails.root.join("spec/factories/**/*.rb")].each {|f| require f}
spec_helper中的

? 那为我做了

答案 3 :(得分:0)

如果您的rspec配置正在加载spec / support下的所有内容,那么您可以将工厂目录放在那里。

请参阅此帖子:http://www.codeography.com/2010/04/30/using-factory_girl-and-rspec-with-rails-3.html