Cover by Leonard Richardson, Lucas Carlson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

17.9. Testing Code That Uses External Resources

Credit: John-Mason Shackelford

Problem

You want to test code without triggering its real-world side effects. For instance, you want to test a piece of code that makes an expensive network connection, or irreversibly modifies a file.

Solution

Sometimes you can set up an alternate data source to use for testing (Rails does this for the application database), but doing that makes your tests slower and imposes a setup burden on other developers. Instead, you can use Jim Weirich's FlexMock library, available as the flexmock gem.

Here's some code that performs a destructive operation on a live data source:

	class VersionControlMaintenance

	  DAY_SECONDS = 60 * 60 * 24

	  def initialize(vcs)
	    @vcs = vcs
	  end

	  def purge_old_labels(age_in_days)
	    @vcs.connect
	    old_labels = @vcs.label_list.select do |label|
	      label['date'] <= Time.now - age_in_days * DAY_SECONDS
	    end
	    @vcs.label_delete(*old_labels.collect{|label| label['name']})
	    @vcs.disconnect
	  end
	end

This code would be difficult to test by conventional means, with the vcs variable pointing to a live version control repository. But with FlexMock, it's simple to define a mock vcs object that can impersonate a real one.

Here's a unit test for VersionControlMaintenance#purge_old_labels that uses Flex-Mock, instead of modifying a real version control repository. First, we set up some dummy labels:

	require 'rubygems'
	require ' flexmock' require 'test/unit' class VersionControlMaintenanceTest < Test::Unit::TestCase ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required