Narf: A Ruby Micro Test Framework
source link: https://www.devroom.io/2011/02/11/narf-a-ruby-micro-test-framework/?utm_campaign=Feed%3A+ariejan+%28ariejan%7Cdevroom.io%29
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
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
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?
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK