A Ruby Test Framework in One Line

May 23, 2008

Time for a little Friday fun with Ruby. I love Ruby for things like this. I realize this has little practical usage, but the fact that it's possible says a lot about the language. You can build a test "framework" in one line of code in Ruby. Let's say we are going to write a method that take 0 to n arguments and adds them up. So following TDD, we write the tests first:

tests = {
  "sum" => 0,
  "sum(7)" => 7,
  "sum(2, 3)" => 5,
  "sum(2, 3, 5)" => 10
}

The tests are defined in a hash where the key is the code to be tested in a string and the value is the expected result. Next we write our implementation:

def sum(*args)
  (args || 0).inject(0){|s,e| s+e}
end

And finally, we create and execute our test framework in one line of code:

tests.each{|e,v| puts((r=eval(e))==v ? ". #{e}" : "! #{e} was '#{r}', expected '#{v}'")}

The output looks like this:

. sum
. sum(2, 3, 5)
. sum(7)
. sum(2, 3)

If we change one of our tests to show a failure, you get this:

. sum
. sum(2, 3, 5)
. sum(7)
! sum(2, 3) was '5', expected '8'

Posted in Technology | Tags Ruby

Comments Comments Feed

1. cute! I like the simplicity of the runner.

But your impl looks flawed.... shouldn't it be:

args.inject(0) {|s,e| s+e}

the || 0 part would only help you if you explicitly passed in nil or false. You might as well blow up if they're passing in bad data.

# Posted By Ryan Davis on Friday, May 23 2008 at 7:19 PM

2. @Ryan

Good point, for some reason I was thinking that passing no args would mean that args would be nil, but it is an empty array. I think this is the right implementation:

args.inject(0){|s,e| s+e.to_i}

Which allows sum(nil, "1", 2) to return 3, which of course I was easily able to add a test for. Yay for TDD!

# Posted By Paul Barry on Friday, May 23 2008 at 9:09 PM

3. Nice one-liner :-)

I've been inspired by this and built a more robust one, but it's 20 lines long :P

def MTest(tests)
if tests[0].is_a?(String) then puts tests.shift end
threads = []
results = {:pass => 0, :fail => 0, :err => 0}
tests.each do |t|
e,p,v = *t
threads << Thread.new do
begin
puts(if (r = p.call) == v
results[:pass] += 1
". #{e}"
else
results[:fail] += 1
"! #{e} was #{r}, expected #{v}"
end)
rescue => x
results[:err] += 1
puts "@ #{x.class} at line #{x.backtrace[0].split(':')[1]}"
end
end
end
threads.join
results
end

This allows you many tricks like naming your tests, don't abort on exceptions but show a notice and get a summary for your tests.

# Posted By François Vaux on Friday, May 30 2008 at 5:23 AM

4. I forgot to notice that the test format is now as follows :

tests = [
  "= Some Basic Tests =",
  ['true', proc { true }, true],
  ['true', proc { false }, true],
  ['sum(2,5)', proc { sum(2,5) }, 7]
]

And you just have to call MTest(tests)

(sorry for screwing the indent in my last post)

# Posted By François Vaux on Friday, May 30 2008 at 5:25 AM

5. outstanding!

# Posted By Kerry Gunther on Tuesday, August 5 2008 at 3:55 PM

6. Devver, a TechStars startup, is releasing its developer service to speed up running Ruby testing frameworks.

http://www.pupuweb.com/blog/devver-speed-up-ruby-testing-frameworks/

# Posted By Alex Lim on Tuesday, June 23 2009 at 9:42 AM

7. brian atwood maniac pumps the perfect wear-with-everything color. These wardrobe staples have 5" stiletto heels and hidden 1 1/2" seamless platforms. These Brian Atwood 'Loca' studded pumps are so ravishing, that I'd totally be willing to pop an aspirin before wearing them. And I really lovebrian atwood mesh sandals and Brian Atwood Asymmetric Patent Pumps.brian atwood nude patent leather katie lee pumps. Bold shoes like these sculptural purple suede Brian Atwood 'Lola' pumps make an outfit. purple suede Brian Atwood 'Lola' pumpswith a heel that measures approximately 140mm / 5.5 inches with a 30mm / 1 inch concealed platform. Brian Atwood pumps have a closed toe, cutout detail at arch with elasticated straps and a leather sole.
Herve Leger Dress shop specialises in superior Herve Leger Dress, provides hundreds of discount and fashion Herve Leger Dress, sexy Herve Leger Dress, Herve Leger Skirt, disount Herve Leger Dress-a professional Herve Leger Shop.

# Posted By Brian Atwood maniac pumps on Saturday, August 28 2010 at 3:22 AM

8. Wonderful brian atwood shoes for your style.BRIAN ATWOOD High-heeled sandals Purple is in stock in our store only one size in 36.5 EU. Elegant purple color, you will like it.
And these Pink Brian Atwood Maniac Patent Platform Pumps not only romantic and gorgeous too! It's patent leather leave us sunshine warmness and sexy!
When I original saw these brian atwood loca studded pumps in a metallic version, a while ago, I likeable them OK, but now I am going unhinged for the lavender version!
I really love brian atwood nico patent pump.
And this year, brian atwood maniac pumps are so hot among stars, I saw many times that Victoria-Beckham wearing them on the show time.
If you don’t know about brian atwood…You should. When everyone else is obsessing over the latest pair of Loubs or YS’L’s it’s very easy to overlook awesome shoe lines and designers who push the envelope. brian atwood is one of those designers.I’m a fan of his lines because Atwood really sets out to make his shoes a conversation piece. The use of alternative textures and fabrics makes brian atwood shoes unique. When wearing his shoes you are guaranteed a compliment from someone and a definate shoe in for best footwear. So ladies (and gents) get into these! And I know my card carrying “Shoe Wh*res” are going to love these!
Buy brian atwood shoes at http://www.brianatwoodcom.com. Buy brian atwood pumps at http://www.brianatwoodcom.com/brian-atwood-brian-atwood-pumps-c-65_67.html.
When I original saw these brian atwood loca studded pumps in a metallic version, a while ago, I likeable them OK, but now I am going unhinged for the lavender version!
When it comes to intricate detailing and superb craftsmanship, you know a pair of brian atwood lexia is worth the investment.
Back by popular demand... brian atwood maniac tan, the perfect wear-with-everything color. These wardrobe staples have 5" stiletto heels and hidden 1 1/2" seamless platforms. In a beautiful, very neutral nude tan.
brian atwood whip snake shoe with Exotic whipsnake hidden platform and back metal inset.
Take a walk on the wild side with Atwood Jagger printed knee-high boots. Style them knee high to add sass to an LBD or wear them with the fold-over flap turned up to work this season's hot over-the-knee trend.
brian atwood cage peep Price: $228. 140mm Covered heel. Rounded peep toe. 40mm covered platform. Interwoven cut outs around front. Ankle strap with adjustable metal buckle. Leather insole and lining. Leather sole. Made in Italy.
When it comes to intricate detailing and superb craftsmanship, you know a pair of brian atwood crystal court shoe is worth the investment.
Brian Atwood Platform Chain Pumps with A silver chain scales the lace-up back of this vamped-up pumps.
brian atwood snakeskin platforms is the classic and the elastic heel detail was used again from last Fall.
brian atwood patent leather and mesh Futuristic patent leather style with mesh details and contrast stitching.
Heel measures approximately 95mm/ 3.5 inches. Let your feet do the talking in brian atwood dorota shoes. Wear this chic style with off-duty denim or to liven up office looks.

# Posted By Brian Atwood loca studded pumps on Saturday, August 28 2010 at 3:26 AM

9.
A grand wedding on the beach may be the common dream of most single girls. The bright sunshine, the blue sky and the open sea can satisfy all the demands of the romantic girls. Of course, everything will be perfect with a beach wedding dresses.
Every woman deserve the most beautiful wedding dresses at her special day!The most beautiful smile in the word is belong to the brides when she find her wedding dresses!Love is the time when you slows down in front of the shops selling wedding dresses.
Make the day of your engagement a special one with a A-line or princess wedding dresses!Step like a goddess in tea- length ball gowns,formal ball gowns,victorian ball gowns,debutante ball gowns,prom ball gowns, contemporary ball gownsand vintage ball gowns available in chiffon, organza, silk and satin only at weddingdressesnow.com.
Congratulations! Your little daughter is getting married! But being the mother of the bride (or MOB) is not an easy role. Once upon a time mothers of the bride did most of the wedding planning, and thus got to have their own dreams realized. First of all, choose one from the perfect mother of the bride dresses for yourself here and to be the most elegant mother of bride!
Flower girl dresses must be the perfect accessory for the bride's dress. The flower girls look like the bells ring in the wedding announcements as they toll down the aisle one by one or hand in hand. If you are having flower girls at your wedding, take a look at these beautiful selection of Flower girl dresses from http://www.weddingdressesin.com.

# Posted By A line wedding dresses on Saturday, August 28 2010 at 3:27 AM

10.
Diamond earrings and tiffany silver bracelets can be a romantic gift for any occasion. These can be as simple as a single stone silver tiffany earrings or as elaborate as chandelier silver tiffany earrings embellished with numerous stones. It is important to keep in mind the individual you are buying the gift for. If the recipient of the gift would like something that they can wear every day, tiffany promise rings are the way to go. However if the gift recipient enjoys getting dressed up for a night on the town or goes to formal affairs on occasion, the chandelier tiffany inspired rings are the perfect gift.


While buying a FM transmitter for your car, make sure about few important things. Any fm transmitter house can be easily connected to the headphone jack easily. This is not the case with MP3 player as it doe not connect to your car’s player. In any case, you are unsure about the type of FM transmitter to be purchased, go for the Universal FM transmitter. A Universal pll fm transmitter is compatible with most of the regular headphone jacks. These FM transmitters can charge your MP3 player while connected through the car’s cigarette lighter. To achieve this purpose, you should buy a FM transmitter which connects with MP3 player in your car.
High-tech will take you more surprise. fm stereo transmitterand Digital fm transmitter
will make us realize the power existing. radio station transmitter, Please let us enjoy the magic power together.And there are some new products whole house fm transmitter

# Posted By radio station transmitter on Wednesday, September 1 2010 at 8:02 AM

11. Find ugg and Australian sheepskin boots, learn the history behind the Ugg boot, and when and what to wear with Cheap ugg boots, as well as cleaning and caring forAuthentic Ugg boots,Cheap ugg cardy boots,20%-40% high discount

# Posted By p on Wednesday, September 1 2010 at 2:09 PM

12.

Cheap nfl jerseys are your best choice,a newly released innovative product that will discounted nfl jerseys help you in your sport, or a one of a kind toddler nfl jerseys collectible that you will keep in your family for generations.Quality first,infant nfl jerseys Customer forever, GUARANTEE SHIPPING is our persistent tenet.

# Posted By fewrewree on Wednesday, September 1 2010 at 7:19 PM

13. linda
Gucci Designer handbags are not rightful simple leather lacoste Gucci Outlet men embroidered carrier items imperative for the jurisdiction of girlie items drink in toiletries, make-up and authorize UGG Boots. No girlfriend! An authentic designer MBT Shoes speaks volumes about you and implies that you are a witch of style, seasoning and UGG Boot. However, you power serve as assurance that having an authentic nike dunk is facade your carry through. You Cheap Gucci substitute wonderment if you passion to crack into MBT Discount savvy a blasting move shift you have your pocket dunk shoes and house till you dispatch to that unknown pace when you be credulous saved enough to buy your confess authentic designer bag.

# Posted By nike dunk on Thursday, September 2 2010 at 2:09 AM

14. Louis Vuitton replica
replica louis vuitton
replica handbag
replica bags
replica bag
LV

# Posted By ss on Thursday, September 2 2010 at 7:42 AM

Add a Comment

(If you leave this blank, your IP address will be displayed instead)

(Optional, will not be displayed on the site)