Testing and Mocking

Testing via mocking in Ruby with alternatives for Perl.

Of the languages that I have used in my professional career, Ruby is the one that makes testing easy and fun. It has an easy to understand testing framework and mocking out external classes, most of the time, is very simple. For example:

class Sauron
__def wants
____"the ring"
__end
end

def Gandalf
__def wants
____"peace"
__end
end

class MiddleEarth
__def who_wants_what
____if (Gandalf.wants == peace and Sauron.wants == "the ring") then
______return "war"
____else
______return "peace"
____end
__end
end

Lets say that we have to test out Gandalf or Sauron.
Gandalf.wants.should eql "peace"
Sauron.wants.should eql "the ring"

The above test code is called RSpec and is very simple and easy to understand. Whether it is a Business Analyst or a Project Manager or even your mother, she can fully understand the required behaviour or Gandalf or Sauron.

But what if we had to unit test MiddleEarth? Then we would have to mock Gandalf and Sauron together and alternately to test all code paths. RSpec makes that easy.
Gandalf.should_receive(:wants).and_return("something")
Sauron.should_receive(:wants).and_return("something else")

If either method of either class expected arguments, that too we can deal with.
Sauron.should_receive(:wants).with(something).and_return("something else")

So there you go, testing and mocking made inherently easy with Ruby and its testing frameworks. But how does it compare to the old language of Perl. Perl too, now has a very similar testing framework to RSpec, called Test::Expectation. And for mocking out external influences when unit testing, we have Test::MockObject and Sub::Override.

And if we wanted to business test in either language, cucumber can sit on top of both, although inherently it works much more readily with Ruby/RSpec.