Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

In Place Testing for Ruby methods (See related posts)

This is something kinda experimental I'm working on. Testing is cool, but I hate that it's separate from my code. Perhaps that's stupidity on my part, but I wanted to see if there's a way to bring the lowest level of testing directly into the class..

module InPlaceTesting
  def self.included(klass)
    old_method_added = klass.method(:method_added)
    new_method_added = lambda do |m|
      @@current_method = m
      old_method_added.call m
    end
    
    # Next line inspired by http://utils.ning.com/ruby/dbc.rb by Brian McCallister and Martin Traverso
    (class << klass; self; end).send :define_method, :method_added, new_method_added
    
    class << klass
      def given(*args)
        self.new.send @@current_method, *args
      end
      def method_should(message, params)
        unless params[:return] == params[:when]
          puts "\"#{@@current_method}\" fails to #{message} (returns #{params[:when]} instead of #{params[:return]})"
        end
      end
    end
    
  end
  
end

class DumbClass
  include InPlaceTesting

  def add(x,y) 
    x + y
  end
  method_should "add 5 and 4", :return => 9, :when => given(5, 4)

  def subtract(x,y) 
    x - y
  end 
  method_should "subtract 5 from 14", :return => 9, :when => given(14,5)
  
  def increment(x)
    x + 1
  end
  method_should "increment 12", :return => 13, :when => given(12)
end

Comments on this post

peter posts on Apr 02, 2007 at 05:28
Of course, one major flaw with this is that it doesn't even work on the object level yet ;-) There's no context, no mock, etc..
Badal posts on Apr 02, 2007 at 05:48
but still clever !
peter posts on Apr 02, 2007 at 08:48
It doesn't need much work to get it more functionally complete, but really a lot of thought as to the nicest way to structure it..

You need to create an account or log in to post comments to this site.


Click here to browse all 5140 code snippets

Related Posts