Friday, July 1, 2011

RSpec like DSL in Test::Unit for acceptance testing.

I have project where I have to use Test::Unit. Fine, but I am used to RSpec DSL, especially when it comes to user stories (features). So, here is simple module that shows how you easily can use RSpec-like expressions in default testing framework.

module Test::Unit::UserStory
class UserStoryTestCase < ActionController::IntegrationTest
class << self
attr_accessor :description
alias :it :test
def criteria(name, options = {}, &block)
klass = create_class(name, self, &block)
helper_klass = options[:js] ? CapybaraJavascriptTestHelper : CapybaraTestHelper
klass.send(:include, helper_klass)
klass
end
def background(&block)
define_method(:setup, &block)
end
end
end
def story(name, description, options = {}, &block)
klass = create_class(name, UserStoryTestCase, &block)
klass.description = description
klass
end
def create_class(name, superclass, &block)
klass = Class.new(superclass, &block)
name = name.gsub(/(^\d*|\W)/, ' ').lstrip
klass_name = name.gsub(/(^[a-z]|\s+[a-zA-Z])/).each do |match|
match.lstrip.upcase
end
Object.const_set klass_name, klass
end
end

Just save that module in a file that will be required by your test helper and include in you test unit spec.

require File.expand_path(File.dirname(__FILE__) + "/../test_helper")
include Test::Unit::UserStory
story "Create the thing", %{
As a user
I want to create something
In order to show something
} do
criteria "without js when logged in" do
it "does something"
end
criteria "when logged in", :js => true do
background do
login_as(:me)
end
it "should be easy to create"
it "should be able to create something" do
end
end
end

With Test::Unit::Feature you have a simple DSL. Soon we'll publish in on github as a gem. Now it works with Ruby 1.8.7 and Rails 2.3.10. I didn't test it with the latest stuff.

Done with Jorge :)

No comments:

Post a Comment