这是我的Gemfile配置:
group :development, :test do
gem 'rspec-rails'
gem 'factory_girl', '~>2.0.0.beta1'
gem 'factory_girl_rails', :git => 'https://github.com/thoughtbot/factory_girl_rails.git', :tag => 'v1.1.beta1'
end
这是我的spec_helper.rb
# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require "factory_girl"
# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
Dir[Rails.root.join("spec/factories/**/*.rb")].each {|f| require f}
我将factories
文件夹添加到LOAD_PATH中,因为我希望将它们保存在一个单独的文件夹中。
这是我的factories.rb
文件:
需要File.expand_path(File.dirname(FILE) +‘././spec_helper’)
Factory.define(:user) do |f|
f.country("China")
... other attributes here
end
当我使用rake spec:models
运行测试时,我得到如下信息:
spec/factories/factories.rb:1: syntax error, unexpected tCONSTANT, expecting $end
我发现这源于factory_girl
的find_definitions
方法。我尝试自己调用它,从spec_helper中调用它,但是它没有改变任何东西。
** Invoke spec:models (first_time)
** Invoke db:test:prepare (first_time)
** Invoke db:abort_if_pending_migrations (first_time)
** Invoke environment (first_time)
** Execute environment
rake aborted!
C:/rails/rcproj/spec/factories/factories.rb:1: syntax error, unexpected tCONSTANT, expecting
$end
f.count...er) do |f|
^
C:/Ruby187/lib/ruby/gems/1.8/gems/activesupport-3.0.5/lib/active_support/dependencies.rb:239:in `req
uire'
C:/Ruby187/lib/ruby/gems/1.8/gems/activesupport-3.0.5/lib/active_support/dependencies.rb:239:in `req
uire'
C:/Ruby187/lib/ruby/gems/1.8/gems/activesupport-3.0.5/lib/active_support/dependencies.rb:225:in `loa
d_dependency'
C:/Ruby187/lib/ruby/gems/1.8/gems/activesupport-3.0.5/lib/active_support/dependencies.rb:596:in `new
_constants_in'
C:/Ruby187/lib/ruby/gems/1.8/gems/activesupport-3.0.5/lib/active_support/dependencies.rb:225:in `loa
d_dependency'
C:/Ruby187/lib/ruby/gems/1.8/gems/activesupport-3.0.5/lib/active_support/dependencies.rb:239:in `req
uire'
C:/Ruby187/lib/ruby/gems/1.8/gems/factory_girl-2.0.0.beta2/lib/factory_girl/find_definitions.rb:20:i
n `find_definitions'
C:/Ruby187/lib/ruby/gems/1.8/gems/factory_girl-2.0.0.beta2/lib/factory_girl/find_definitions.rb:19:i
n `each'
C:/Ruby187/lib/ruby/gems/1.8/gems/factory_girl-2.0.0.beta2/lib/factory_girl/find_definitions.rb:19:i
发布于 2011-03-14 12:50:34
我认为问题与你们工厂的装货有关。只需将此写入您的test_helper.rb文件
require 'factory_girl'
Dir.glob(File.dirname(__FILE__) + "/factories/*").each do |factory|
require factory
end
OR
require 'factory_girl'
FactoryGirl.find_definitions
发布于 2011-10-12 20:16:20
我也有过同样的问题,但事实证明,我只是把我的文件命名错误(factories.rb.rb,感谢Netbeans)。不过,我发现了一些对这个页面有用的东西。
测试/factories.rb规范/factories.rb测试/工厂/*..rb spec/工厂/*..rb
在test_helper.rb中放置以下内容会导致双重加载:
需要“factory_girl”Factory.find_definitions
这导致我得到了一个`add_as': Already defined: <factory name>
错误。
https://stackoverflow.com/questions/5298392
复制相似问题