DZone 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

Snippets has posted 5883 posts at DZone. View Full User Profile

In Place Testing For Ruby Methods

04.02.2007
| 3663 views |
  • submit to reddit
        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

Snippets Manager replied on Mon, 2012/05/07 - 2:37pm

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..

Snippets Manager replied on Mon, 2007/04/02 - 5:46am

but still clever !

Snippets Manager replied on Mon, 2012/05/07 - 2:37pm

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..