+++ date = "2011-02-11" title = "Narf: A Ruby Micro Test Framework" tags = ["Ruby", "Test", "testing", "bdd", "tdd", "agile"] slug = "narf-a-ruby-micro-test-framework" +++ 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* ``` ruby 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: ``` ruby 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: ``` shell $ ruby my_method.rb ! FAIL - Count zero rubies ! FAIL - Count one ruby ! FAIL - Count one RuBy ``` Now, implement your method... ``` ruby def count_rubies(text) text.match(/(ruby)/i).size end ``` And re-run your tests: ``` shell $ 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? [Need codez?][1] [1]: http://github.com/ariejan/narf