devroom.io/content/posts/2011-02-11-narf-a-ruby-micro-test-framework.md

92 lines
2.0 KiB
Markdown
Raw Normal View History

2015-03-26 11:28:08 +00:00
+++
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*
2017-03-20 15:35:19 +00:00
``` ruby
def assert(message, &block)
puts "#{"%6s" % ((yield || false) ? ' PASS' : '! FAIL')} - #{message}"
end
```
2015-03-26 11:28:08 +00:00
(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:
2017-03-20 15:35:19 +00:00
``` ruby
def count_rubies(text)
# TODO
end
2015-03-26 11:28:08 +00:00
2017-03-20 15:35:19 +00:00
#--- Ruby Micro Test Framework
def assert(message, &block)
puts "#{"%6s" % ((yield || false) ? ' PASS' : '! FAIL')} - #{message}"
end
#---
2015-03-26 11:28:08 +00:00
2017-03-20 15:35:19 +00:00
#--- Tests
assert "Count zero rubies" do
count_rubies("this is Sparta!") == 0
end
2015-03-26 11:28:08 +00:00
2017-03-20 15:35:19 +00:00
assert "Count one ruby" do
count_rubies("This is one ruby") == 1
end
2015-03-26 11:28:08 +00:00
2017-03-20 15:35:19 +00:00
assert "Count one RuBy" do
count_rubies("This is one RuBy") == 1
end
```
2015-03-26 11:28:08 +00:00
Now, simple save this file and feed it to ruby:
2017-03-20 15:35:19 +00:00
``` shell
$ ruby my_method.rb
! FAIL - Count zero rubies
! FAIL - Count one ruby
! FAIL - Count one RuBy
```
2015-03-26 11:28:08 +00:00
Now, implement your method...
2017-03-20 15:35:19 +00:00
``` ruby
def count_rubies(text)
text.match(/(ruby)/i).size
end
```
2015-03-26 11:28:08 +00:00
And re-run your tests:
2017-03-20 15:35:19 +00:00
``` shell
$ ruby my_method.rb
PASS - Count zero rubies
PASS - Count one ruby
PASS - Count one RuBy
```
2015-03-26 11:28:08 +00:00
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