Spec Improvements

We were fixing some failing specs in one of our project, we noticed beside failures the spec timings was too high. We spent time not only to fix also improve the performance. During this process we learned few good practices and removed bad things we added earlier which helped us improved the performance.

  1. We had good amount of setup code for specs, for which we were using let statements. We can move the setup into a before(:all) block, replacing lets with instance variables. This will create the data only once, and as long as we never change the data between tests. This improved the timings considerably.

  2. We had lots of 'before each', which should be strictly avoided. Before each will create the data for each assertions, which is bad. Although there are areas where it is irreplaceable.

  3. Test only what your method does, avoid unecessary assertions. Avoid count assertions instead use include, avoid eq assertions if its an array, as order can be random, better use match_array.

  4. Empty spec files generated when you generate model with just require ‘spec_helper’ are there to slow tests, avoid it!

  5. If there is huge setup involved before specs, its an indication that we are not using the factory properly.

  6. Use of initialize_with will be of great help, if you want to reuse an record:

    factory :category do
    category { FactoryGirl.generate :label }
    initialize_with { Category.find_or_create_by_category(category) }
    end

These are few small tips which can make good improvement in your rspec suite.

For more refer this: http://betterspecs.org/, this link has good comparision of good vs bad while writing rspec.

When to use before :all, before :each, let and let!, please refer this SO answer, describes very nicely:

http://stackoverflow.com/a/15648208/648372

Another nice article on let, http://stackoverflow.com/questions/5359558/when-to-use-rspec-let