DRY your RSpecs

Inspired by reading DRY your Scopes

Sometimes I find that I can write a bunch of tedious specs in a simplified manner described below.

It started innocently enough. As a certain set of features were growing, I found that I was writing repetitive tests like this:

context 'specialty patient section' do
  it('has specialty patient') { @plain_html.should =~ /Specialty Patient/ }
  it('has specialty patient trauma criteria') { @plain_html.should =~ /Trauma Activation/ }
  it('has specialty patient airway') { @plain_html.should =~ /Advanced Airway/ }

So I threw that aside and simplified:

# Test that certain sections only display when there are data to be shown.
dynamic_sections = ['Vital Signs', 'ECG', 'Flow Chart', 'Initial Assessment', 'Narrative',
                    'Specialty Patient — ACS', 'Specialty Patient — Advanced Airway',
                    'Specialty Patient — Burns', 'Specialty Patient — Stroke', 'Specialty Patient — CPR',
                    'Specialty Patient — Motor Vehicle Collision', 'Specialty Patient — Trauma Criteria',
                    'Specialty Patient — Obstetrical', 'Specialty Patient — Spinal Immobilization',
                    'Influenza Screening', 'SAD (Psychiatric Ax)',
                    'Incident Details', 'Crew Members', 'Insurance Details', 'Mileage', 'Additional Agencies',
                    'Next of Kin', 'Personal Items', 'Transfer Details']

  context 'dynamic sections' do
    let(:p) {
      xml_str = ...some XML...
      Parser.new(xml_str) }
    let(:r) { Renderer::Customer1::HTML.new(p) }
    let(:html) { r.render }
    context ', when there is no info, ' do
      dynamic_sections.each do |s|
        it("should not have: #{s}") { html.should_not =~ /#{s}/ }

Simple stuff… nothing amazing. Simply using ruby’s language to simplify the maintenance of the specs. When a new section is added to the HTML template, it merely needs to be added to the array. And since it is generating actual specs, you preserve meaningful error messages:

Renderer dynamic sections , when there is no info,  should not have: Specialty Patient — Trauma Criteria

The intent of the test is very clear, and 24 lines of “it” specs are avoided.

1 thought on “DRY your RSpecs”

Comments are closed.