【问题标题】:Rspec extremely slowRspec极慢
【发布时间】:2013-03-18 07:21:53
【问题描述】:

即使使用 guard 和 spork,我的 rspec 测试似乎也运行得非常缓慢。

Finished in 5.36 seconds
13 examples, 2 failures

我知道我可以做几件事来优化我的测试并减少与数据库的交互,但我强烈怀疑 spec_helper 的设置不正确。我在使用 mongoid 的 Rails 3.2.11 上。每次运行后都会清理数据库清理器。

spec_helper.rb

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

  Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
  DatabaseCleaner[:mongoid].strategy = :truncation

  RSpec.configure do |config|
    config.infer_base_class_for_anonymous_controllers = false
    config.order = "random"
    config.filter_run focus: true
    config.filter_run_excluding :remove => true
    config.run_all_when_everything_filtered = true
    config.include Mongoid::Matchers
    config.include Capybara::DSL
    ActiveSupport::Dependencies.clear
  end
end


Spork.each_run do
  Fabrication.clear_definitions
  RSpec.configure do |config|
    config.before(:each) do
      DatabaseCleaner.clean
    end
  end
end

更新:问题出在我的一项测试上。花了3秒钟。请检查@Sam Peacey 对我用来获得以下结果的命令的回答

Dynamic Model should destroy collection when related source is destroyed
    2.46 seconds ./spec/models/dynamic_model_spec.rb:10
Dynamic Model Validations should validate uniqueness
    0.66357 seconds ./spec/models/dynamic_model_spec.rb:69

【问题讨论】:

  • 5 秒还不错。 Ruby 不是你知道的 C...
  • 13 次测试?我见过人们在 5-6 秒内运行 200 多个测试。差异似乎太大了。
  • 我已经让 Ruby VM 需要大约 3-4 秒才能启动,这是在最近的硬件上。
  • 没错。但是 Rspec 不会从它的日志中排除那个时间吗?所以 5 秒应该只解决测试吧?
  • 我同意这对于仅 13 次测试来说很慢,您是否尝试过删除数据库清理器调用只是为了看看这是否是罪魁祸首(您的一些测试很可能会失败,但您可能会找出问题所在是)?

标签: ruby-on-rails ruby-on-rails-3 rspec-rails spork database-cleaner


【解决方案1】:

您可以通过使用 -p / --profile 标志运行 rspec 来分析您的规范:

rspec spec -p [-drb, and whatever else]

这将列出 10 个最慢的示例及其执行时间。您可以通过为 -p 标志提供可选计数来更改默认值 10。更多信息请使用rspec --help

【讨论】:

    【解决方案2】:

    在我的情况下,问题是在 development ENV 中运行的 RSpec,而不是在 test 中。我通过在spec_helper.rb 中添加ENV['RAILS_ENV'] ||= 'test' 作为第一行 来修复它 - 否则它不起作用。

    我还必须推荐非常有用的 gem 来分析代码 - test-prof

    【讨论】:

      猜你喜欢
      • 2013-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-29
      • 2013-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多