Mocking at NovaRUG Tomorrow

On the heels of Mark's contribution to the deployment panel discussion, I'll be doing a quick talk on mocking libraries in Ruby at tomorrow's NovaRUG meeting. Back in January, I was blown away by the demo of FlexMock that Jim Weirich gave during his "Red, Green, Refactor" talk at the Rails Edge conference. Since then, we have been making extensive use of both FlexMock and Mocha when we need to control the behavior of objects inside the code we're testing. This is especially useful when our models rely on external resources (e.g. resources fetched via HTTP), but it also comes in handy when we want to hone in on testing a single piece of code:
 class Die def roll rand(6) + 1 end end 
In our tests, we can stub out the behavior of Kernel#rand so that we're working with a defined state (using FlexMock):
 require 'rubygems' require 'test/unit' require 'flexmock' require 'flexmock/test_unit' require 'die' class DieTest < Test::Unit::TestCase def test_roll_when_rand_returns_zero_should_return_one die = Die.new flexmock(die).should_receive(:rand).once.with(Integer).and_return(0) assert_equal 1, die.roll end end 
I'll be testing a simple bit of Ruby code and comparing both libraries side-by-side to discuss their usage. Mocking is a concept that I've been interested in for a while (and have been writing about more and more), so I'm really looking forward to the event. Hope to see you there.

Patrick is development director in Viget's Boulder, CO, office. He writes clean Ruby code and automates system infrastructure for clients such as Shure and Volunteers of America.

More posts by Patrick