I'm a happy user of RSpec, Cucumber and sometimes Steak. Great tools to write specs and features and prove my application does what it's supposed to do. But sometimes I have the need for something more light weight. For example, sometimes I need to write a single ruby method. Just something 'quick' to import a file, convert some data or whatever. Being a good citizen I want to test that method.
Using RSpec or Cucumber here just seems wrong here. So, I've implemented my own Ruby Micro Test Framework: Narf
def assert(message, &block) puts "#{"%6s" % ((yield || false) ? ' PASS' : '! FAIL')} - #{message}" end
(Yes, that's it.)
With this simple method, added to your ruby file, you can test your method. And example:
Let's say you're going to write a method that counts how often the word 'ruby' occurs in a given String:
def count_rubies(text) # TODO end #--- Ruby Micro Test Framework def assert(message, &block) puts "#{"%6s" % ((yield || false) ? ' PASS' : '! FAIL')} - #{message}" end #--- #--- Tests assert "Count zero rubies" do count_rubies("this is Sparta!") == 0 end assert "Count one ruby" do count_rubies("This is one ruby") == 1 end assert "Count one RuBy" do count_rubies("This is one RuBy") == 1 end
Now, simple save this file and feed it to ruby:
$ ruby my_method.rb ! FAIL - Count zero rubies ! FAIL - Count one ruby ! FAIL - Count one RuBy
Now, implement your method...
def count_rubies(text) text.match(/(ruby)/i).size end
And re-run your tests:
$ ruby my_method.rb PASS - Count zero rubies PASS - Count one ruby PASS - Count one RuBy
So with the addition of just a single method you can fully TDD/BDD your single method Ruby code. Pretty need, huh?