2012-02-26 88 views
6

我試圖在每次運行測試之間重置工廠女孩的「序列」。rspec和工廠女孩的重複工廠錯誤?

factory_girl 2.6.0factory_girl_rails 1.7.0

我認爲要做到這一點,我必須重新加載FactoryGirl定義。我這樣做是在spec_helper.rb的最後幾行:

require 'rubygems' 
require 'spork' 
#uncomment the following line to use spork with the debugger 
#require 'spork/ext/ruby-debug' 

Spork.prefork do 
    ENV["RAILS_ENV"] ||= 'test' 
    require File.expand_path("../../config/environment", __FILE__) 
    require 'rspec/rails' 
    require 'rspec/autorun' 
    require 'capybara/rspec' 

    require "rails/application" 
    Spork.trap_method(Rails::Application::RoutesReloader, :reload!) 

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

    RSpec.configure do |config| 
    config.mock_with :rspec 

    require 'database_cleaner' 
    config.before(:suite) do 
     DatabaseCleaner.strategy = :transaction 
     DatabaseCleaner.clean_with(:truncation) 
    end 

    config.before(:each) do 
     DatabaseCleaner.start 
    end 

    config.after(:each) do 
     DatabaseCleaner.clean 
    end 

    config.infer_base_class_for_anonymous_controllers = false 

    # For mailer 
    config.include(MailerMacros) 
    config.before(:each) {reset_email} 
    end 

end 

Spork.each_run do 
    # This code will be run each time you run your specs. 
    I18n.backend.reload! 
    Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f } 
    require 'factory_girl' 
    FactoryGirl.definition_file_paths = [File.join(Rails.root, 'spec', 'factories')] 
    FactoryGirl.find_definitions 
end 

添加:

FactoryGirl.definition_file_paths = [File.join(Rails.root, 'spec', 'factories')] 
    FactoryGirl.find_definitions 

信息我下面的錯誤運行rspec spec/

→ bundle exec guard 
Guard uses Growl to send notifications. 
Guard is now watching at '/Rails/projects/MyRailsProject' 
Starting Spork for RSpec 
Using RSpec 
Preloading Rails environment 
Loading Spork.prefork block... 
Spork is ready and listening on 8989! 
Spork server for RSpec successfully started 
Guard::RSpec is running, with RSpec 2! 
Running all specs 
Exception encountered: #<FactoryGirl::DuplicateDefinitionError: Factory already registered: user> 

這似乎是一個複製的時候工廠錯誤,也許它試圖兩次加載工廠女孩,但我不明白爲什麼。

回答

10

它試圖加載所有的工廠兩次,因爲你問它。 更換你到find_definitions電話與

FactoryGirl.reload 

其清除現有的工廠,序列等,然後調用find_definitions