Platinum Partner

In Place Testing For Ruby Methods

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
{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}