Saturday, July 29, 2006

My Ruby Stub

Being new to Ruby, one of the first things I wanted to do was figure out how to apply the testing style I am comfortable with in Java.  Several years ago, Bob Lee and I wrote an IDEA plugin to generate stub-object source files from interface definitions.  For a given interface:

The stub generator would create a class that looks like:

The generated stubs are useful in testing because I can set them up with a return value or exception to simulate some condition that I am trying to test. The methods of the stub keep track of whether they were called and any parameters that were passed to them. This approach follows the state-based testing that Fowler describes, and is central to my own programming style.

In Ruby, the same kind of thing can be accomplished at runtime in a very dynamic way. This unit test demonstrates the kind of thing I am looking for in a stub generator:

The Ruby Stub implementation was tricky to figure out until I learned how to use define_method:

So in my first real foray into a Ruby utility, I was able to create something that does what I need and learn a little about the API in the process. Of course, after savoring the feeling of learning and having written something that I thought was cool, I had a closer look the Stubba API from the Mocha library and realized that I still had a long way to go. Still, the exercise was a useful one; the more I use Ruby the more I really like it.

1 comment:

James Mead said...

Thanks for the mention. I'm glad Stubba looks useful to you. Please let me know if you have any feedback.