Using cucumber and webrat for remote web testing

Cucumber and webrat serve as a powerful combination of tools for testing your web applications, but in its most common mode webrat can only test your application locally. Is it possible, you may ask, to use webrat to test a remote web site? The answer is yes, with a little tweaking. Webrat has a configuration option that tells it to use mechanize (a screen-scraping tool for ruby) instead of the built-in rails view testing system.

You might think that telling webrat to use mechanize instead of its default mode would be as easy as changing the appropriate lines in your env.rb file, like this:

Webrat.configure do |config|
  config.mode = :mechanize
end

Which would of course make sense, but no, they don’t make it that easy for you. Perhaps someday webrat will be smart enough to alter the cucumber environment on your behalf to bring in some of the mechanize features, but for now you need to add some things to the cucumber world manually. Here are the full contents of env.rb:

require 'webrat'

Webrat.configure do |config|
  config.mode = :mechanize
end

class MechanizeWorld < Webrat::MechanizeSession
  require 'spec'
  include Spec::Matchers
end

World do
  MechanizeWorld.new
end

If you’ve already added stuff to your cucumber world then you would want to replace the World block above with this:

module NewMechanizeWorld
  MechanizeWorld.new
end
World(NewMechanizeWorld)

In addition to this, some of your steps may need to be altered to expect mechanize style session attributes. For example, this step looks at the contents of response.body instead of the usual webrat syntax.

Then /^I should see search results about (.*)$/ do |term|
  response.body.should include(term)
end

The full code for a working simple example can be downloaded on github. Hat-tip to Ben Maybe for helping us with this at last night’s URUG meeting.