Close and Go BackBack to Viget

Mocking at NovaRUG Tomorrow

Patrick Reagan
Patrick Reagan, Development Director, July 17, 2007

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.

blog comments powered by Disqus

We're the Developers

at Viget Labs. We write about web development trends, tips, best practices, industry events, and our projects — all with an emphasis on Ruby on Rails.

Contact Us

Have any questions, comments, ideas, or secrets to share? Let us know.


What color is the sky?

Sorry, you need to have Javascript enabled to use this form. (Don't blame us, blame the spammers!) If you'd like to contact us, please visit our Contact page.