I often need to output debugging info in specs when something just isn't working. No sweat, just put in a puts or two, and run the spec.
Of course I'm usually doing this in Textmate using the RSpec bundle, which displays the results in a nice window formatted with html.
But that causes problems with my debugging output
The problem is that the puts output is just raw text so the HTML formatter ignores line breaks.
At one of the Radiant hack fests, either John Long or Adam Williams taught this old dog a simple new trick. The suggestion was to define a new Kernel#rputs method as a wrapper for puts which 'wraps' the arguments in an html
tag. Then just call rputs (the r is for rspec of course) in the spec and or code under test.
This works great as long as you run the specs under RSpec. But if you run them in the shell you see something like this:
$ spec spec/ri_cal/bugreports_spec.rb
Booga booga
this should be another line
.......
Finished in 0.525324 seconds
7 examples, 0 failures
I've been putting up with this minor annoyance for a while, but this morning it struck me that I could define rputs conditionally depending on whether the spec was being run in Textmate or not. The trick is that Textmate defines one or more environment variables whose name starts with 'TM_'. So, without further ado, here's the new fragment from my spec_helper.rb:
module Kernel
if ENV.keys.find {|env_var| env_var.start_with?("TM_")}
def rputs(*args)
puts( *["", args.collect {|a| CGI.escapeHTML(a.to_s)}, ""])
end
else
alias_method
:rputs,
:puts
end
end
With this change, running in the shell now looks like this:
$ spec spec/ri_cal/bugreports_spec.rb
Booga booga
this should be another line
.......
Finished in 0.348086 seconds
7 examples, 0 failures
A nice refinement to my bag of tricks!