Behold! RSpec and autotest get married

It’s been tried before, with Nick Sieger and Philippe Hanrigou both providing some .autotest files to customize autotest for the purposes of RSpec. Using both their code as a template, I’ve come up with a few small changes for my own nefarious purposes. Behold, my .autotest!

Autotest.add_hook :initialize do |at|
# run spec with rcov
if at.respond_to? :spec_command
at.spec_command = %{script/spec --diff unified --colour}
end
end

module Autotest::GnomeNotify

# Time notification will be displayed before disappearing
# automatically
EXPIRATION_IN_SECONDS = 4
ERROR_STOCK_ICON      = "gtk-dialog-error"
SUCCESS_STOCK_ICON    = "gtk-dialog-info"

# Convenience method to send an error notification message
#
# [stock_icon]   Stock icon name of icon to display
# [title]        Notification message title
# [message]      Core message for the notification
def self.notify stock_icon, title, message
options = "-t #{EXPIRATION_IN_SECONDS * 1000} -i #{stock_icon}"
system "notify-send #{options} '#{title}' \"#{message.gsub(%r{"}, "\"")}\""
end

Autotest.add_hook :red do |at|
notify ERROR_STOCK_ICON, "Tests failed",
"#{at.files_to_test.size} test#{'s' if at.files_to_test.size != 1} failed.n" + at.results.scan(%r{'(.*)'}).flatten.first
end

Autotest.add_hook :green do |at|
if at.results.empty?
notify ERROR_STOCK_ICON, "No results", "Did you throw an exception?"
else
notify SUCCESS_STOCK_ICON, "All tests passed, good job!", at.results.scan(%r{d+ example[s]?, d+ failure[s]?}).first
end
end

end

What advantages does this bring? Well for one, you get colored output. For another, you get better notification of successes (number of tests passed, etc.) and failures (a description of the first failure). Even better, you get notified when you throw an exception (for instance, by mistyping the name of a method), which autotest would otherwise report as a success. It also does a dumb shell escape on any single quotes in the message sent to notify-send, so specs with apostrophes don’t break anything.

Of course, I’m sure it completely breaks if you try and use Test::Unit in conjunction, but who uses Test::Unit nowadays?

Update: Please excuse the unindented nature of my code. WordPress has a pathological need to reformat (read: “fuck with”) preformatted text. Because of general unhappiness with WordPress, I’m likely moving away quite soon. Possibly to Typo or Mephisto.