→ test/spec/mini

03 March 2008

If you don’t care about the should syntax, you don’t really need the test/spec gem. This’ll do just dandy.

##
# test/spec/mini
# http://gist.github.com/307649
# chris@ozmm.org
#
def context(*args, &block)
  return super unless (name = args.first) && block
  require 'test/unit'
  klass = Class.new(Test::Unit::TestCase) do
    def self.specify(name, &block) 
      define_method("test_#{name.gsub(/\W/,'_')}", &block) 
    end
    def self.xspecify(*args) end
    def self.setup(&block) define_method(:setup, &block) end
    def self.teardown(&block) define_method(:teardown, &block) end
  end
  klass.class_eval &block
end

And look, it can even test itself:

# ensure setup / spec / teardown order
# also ensure we can define methods inline so `include Helpers` works
context "test/spec/mini" do
  def put(message)
    @messages << message
  end

  setup do
    @messages = []
    put :setup
    assert true
  end

  specify "a specification!" do
    put :specify1
    assert true
  end

  specify "another specification?!" do
    put :specify2
    assert true
  end

  specify "failed spec" do
    put :failed
    flunk
  end

  specify "error spec" do
    put :error
    raise "donut"
  end

  xspecify "disabled spec" do
    put :disabled
    assert true
  end

  teardown do
    put :teardown
    assert true
    Kernel.puts @messages.join(':')
  end
end

Full code is at the gist.