Testing in Ruby on Rails
The main struggle I had when I first started coding in Ruby on Rails was working out how to use tests. Ruby, and Rails, have a great testing framework, but I had no background in knowing how, and what, to test. As I have progressed with the language I have become more confident in writing tests and I am now noticing the benefit of writing them.
A couple of the tools I use in testing are rcov and Heckle. Between these tools you can reveal just how well you are testing your Ruby application.
rcov
With rcov you can run your tests and see which lines of code were executed during the tests. I find this really useful for reminding me which sections of code I have forgotten to write tests for. I use a modification of Mike Clark’s suggestion for running the coverage tests.
namespace :test do
desc 'Measure test coverage'
task :coverage do
system("rcov --rails --text-summary -Ilib --xrefs --html test/unit/*_test.rb test/functional/*_test.rb test/views/*_test.rb test/integration/*_test.rb")
system("open coverage/index.html") if PLATFORM['darwin']
system(”firefox coverage/index.html”) if PLATFORM['linux']
end
end
Note that the firing of Firefox to view the tests on Linux will only work if you can type firefox in a terminal and have it open a web browser for you. If this does not work then you can replace ‘firefox’ with another browser. On Kubuntu (and, so, I assume the rest of the Ubuntu family) sensible-browser will work.
Heckle
While rcov lets you know if a line of code is executed during testing it is useful to know if the line is actually tested. This is where Heckle comes in. It tests your tests.
Simply you run it with
heckle [classname]
and watch it go to work on your code. It takes the code in the class, mutates it in some way, and runs it against your tests. If your tests do not fail when code in the class is mutated then that section of code was never being tested. Simple and effective.
