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
1def assert(message, &block)
2 puts "#{"%6s" % ((yield || false) ? ' PASS' : '! FAIL')} - #{message}"
3end
(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:
1def count_rubies(text)
2 # TODO
3end
4
5#--- Ruby Micro Test Framework
6def assert(message, &block)
7 puts "#{"%6s" % ((yield || false) ? ' PASS' : '! FAIL')} - #{message}"
8end
9#---
10
11#--- Tests
12assert "Count zero rubies" do
13 count_rubies("this is Sparta!") == 0
14end
15
16assert "Count one ruby" do
17 count_rubies("This is one ruby") == 1
18end
19
20assert "Count one RuBy" do
21 count_rubies("This is one RuBy") == 1
22end
Now, simple save this file and feed it to ruby:
1$ ruby my_method.rb
2! FAIL - Count zero rubies
3! FAIL - Count one ruby
4! FAIL - Count one RuBy
Now, implement your method…
1def count_rubies(text)
2 text.match(/(ruby)/i).size
3end
And re-run your tests:
1$ ruby my_method.rb
2 PASS - Count zero rubies
3 PASS - Count one ruby
4 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?