Question

My rspec tests seem to run extremely slow even with guard & spork.

Finished in 5.36 seconds
13 examples, 2 failures

I understand that there are several things I can do to optimize my tests & reduce interaction with the database, but I strongly suspect that the spec_helper has been improperly setup. I'm on rails 3.2.11 with mongoid. Database cleaner cleans up after every run.

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

UPDATE: The problem was with one of my tests. It was taking 3 seconds. Please check @Sam Peacey's answer for the command I used to get the below result

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
Was it helpful?

Solution

You can profile your specs by running rspec with the -p / --profile flag:

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

This will list the 10 slowest examples with their execution time. You can change the default of 10 by providing an optional count to the -p flag. More info by using rspec --help

OTHER TIPS

In my case problem was in RSpec running in development ENV, not in test. I fixed it by adding ENV['RAILS_ENV'] ||= 'test' as a first line in spec_helper.rb - otherwise it didn't worked.

Also I must recommend very useful gem for profiling code - test-prof

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top