branch14log

Help RSpec to help you

07 May 2013

Unfortunately code is not in all cases crafted in a way so that failing specs in RSpec yield meaningful errors. If your own code is to blame, you might want to consider changes here first. In cases where the code is set in stone it might help to make RSpec a little more verbose in case of failing specs. Often enough this results in a lot of 'puts'-statements sprinkled all over your specs until it's finally running, followed by a subsequent removal process to hide all the dirty work. But as soon as this spec fails all the work that is now hidden has to be done again. Obviously there has to be a better way. How about leaving valuable details in the spec but output them only in case of a failure? Wouldn't that be great? Since a failing spec is not being executed you can't check for a failure within the spec. But you can check for a failure of a spec in the 'after each' hook. Only little monkey patching is needed to provide an extra field on RSpec::Core::Example to store your additional message in. A check for example.exception in the hook lets you determine if the spec failed. In case of a failure we'll simply output the additional message nicly formatted as YAML. This is what you'll have to do...
# 1/3 monkey patch rspec to hold an additional message
class RSpec::Core::Example
  attr_accessor :message
end

describe SomeClass do

  # 2/3 output additional message in case of error
  after(:each) do
    if example.exception and example.message
      puts example.message.to_yaml 
   end
  end

  it 'succeed' do
    # here goes you spec setup
    # and right before you use and should-statements
    # 3/3 provide additional message for debugging
    example.message = result.errors
    result.should be_valid
  end
end