Ruby Unit Testing Framework in 44 Lines of Code

unit-testing

When it comes to unit testing, I think that many developers want to do it but project timelines or business requirements make it difficult to provide a convincing case for building it into the scope of the work to be done.

On top of that, I think that the amount of time required to setup and configure testing environments are often higher than they should be, so I appreciate it when I see other projects or developers coming up with creative ways to handle unit testing in a quicker fashion.

Alan Skorkin has written a unit testing framework in 44 lines of Ruby:

module Kernel
  def describe(description, &block)
    tests = Dsl.new.parse(description, block)
    tests.execute
  end
end
class Object
  def should
    self
  end
end
class Dsl
  def initialize
    @tests = {}
  end
  def parse(description, block)
    self.instance_eval(&block)
    Executor.new(description, @tests)
  end
  def it(description, &block)
    @tests[description] = block
  end
end
class Executor
  def initialize(description, tests)
    @description = description
    @tests = tests
    @success_count = 0
    @failure_count = 0
  end
  def execute
    puts "#{@description}"
    @tests.each_pair do |name, block|
      print " - #{name}"
      result = self.instance_eval(&block)
      result ? @success_count += 1 : @failure_count += 1
      puts result ? " SUCCESS" : " FAILURE"
    end
    summary
  end
  def summary
    puts "n#{@tests.keys.size} tests, #{@success_count} success, #{@failure_count} failure"
  end
end

Although this approach misses out on certain aspects of more mature frameworks such as improved messaging, support for mock objects, stubbing out classes, and so on, this is certainly better than simply launching something without testing.

You can read more about his approach and example usage in his original article.

Tom

I write both code and content for this team and I love every minute of it.

What would you like to say?

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>