加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 与rspec和工厂女孩的重复出厂错误?

发布时间:2020-12-17 04:19:44 所属栏目:百科 来源:网络整理
导读:我正试图在我运行的每个测试之间重置工厂女孩的“序列”. (factory_girl 2.6.0和factory_girl_rails 1.7.0) 我认为要这样做,我必须重新加载FactoryGirl定义.我在spec_helper.rb的最后几行中这样做: require 'rubygems'require 'spork'#uncomment the follow
我正试图在我运行的每个测试之间重置工厂女孩的“序列”.

(factory_girl 2.6.0和factory_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,'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>

这似乎是一个重复的工厂错误,也许它试图加载工厂女孩两次,但我不明白为什么.

解决方法

它试图加载你所有的工厂两次,因为你要求它.
将您的调用替换为find_definitions
FactoryGirl.reload

清除现有的工厂,序列等,然后为你调用find_definitions

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读