#!/usr/bin/ruby require 'rubygems' require 'active_support' require 'pp' class String def indent(n) if n >= 0 gsub(/^/, ' ' * n) else gsub(/^ {0,#{-n}}/, "") end end end text = ARGV[0].nil? ? $stdin.read : IO.read(ARGV[0]) text.sub!("require File.dirname(__FILE__) + '/../spec_helper'", "require File.dirname(__FILE__) + '/../test_helper'") text.gsub!(/^describe\s+"?([^"]+?)"? do$/) do |match| c = $1.gsub(/[ \-']/, "_") "class #{c.camelize}Test < Test::Unit::TestCase" end # shared behaviors shared_behaviors = {} text.gsub!(/^describe\s+"?([^"]+)"?,\s*:shared\s*=>\s*true\s+do$/) do |match| orig = $1 name = $1.gsub(/[ \-']/, "_").camelize + "Behavior" shared_behaviors[orig] = name "module #{name}" end text.gsub!(/^(\s*)before\(:each\) do$/, '\1def setup') text.gsub!(/^(\s*)before\(:all\) do\n(.+?)\n\s+end\s+$/m) do |match| indent = $1 body = $2.split($/) body.collect { |b| b.sub(/^\s*/, indent) }.join($/) + $/ end # handle shared behaviors text.gsub!(/^(\s+)it_should_behave_like\s+"(.+?)"/) do |match| "#{$1}include #{shared_behaviors[$2]}" end # convert examples to test methods text.gsub!(/^(\s+)it "(.+?)" do(.+?end)/m) do |match| indents = [$1] mbody = $3 mname = $2.gsub(/[ ']/, "_").gsub(/#/, "") # make some replacements (incomplete) # FIXME: not handled: # - should raise_error mbody.gsub!(/^(\s+)(.+?)\.should(_not)? (.+)/) do |match| indents << $1 subject = $2 negate = $3 == "_not" bang = negate ? "!" : "" _not = negate ? "_not" : "" predicate = $4 retval = case predicate when /^be_(true|false)/ negate = $1 == "true" ? negate : !negate bang = negate ? "!" : "" "#{indents[-1]}assert #{bang}#{subject}" when /^be_/ method = predicate.sub(/^be(_an?)?_/, "") + "?" "#{indents[-1]}assert #{bang}#{subject}.#{method}" when /^==\s*(.+)/, /^eql\((.+)\)/ expected = $1 "#{indents[-1]}assert#{_not}_equal #{expected}, #{subject}" when /^(?:<=?|=?>)/ "#{indents[-1]}assert #{bang}#{subject} #{predicate}" when /^have_?(at_least|at_most|exactly)?\((\d+)\)\.(\w+)/ kind = $1 num = $2 collection = $3 case kind when nil, "exactly" "#{indents[-1]}assert#{_not}_equal #{num}, #{subject}.#{collection}.length" when "at_least", "at_most" op = kind == "at_least" ? (negate ? "<" : ">=") : (negate ? ">" : "<=") "#{indents[-1]}assert #{subject}.#{collection}.length #{op} #{num}" end when /^have\w+\(.+\)$/ method = predicate.sub(/^have(.+?)\(/, 'has\1?(') "#{indents[-1]}assert #{bang}#{subject}.#{method}" when /^include/ method = predicate.sub(/^include/, "include?") "#{indents[-1]}assert #{bang}#{subject}.#{method}" else match end indents.pop retval end "#{indents[-1]}def test_#{mname}#{mbody}" end puts text