class TestEnvironment class Assertion def initialize(msg=nil, blk) @msg, @blk, @passed = msg, blk, false end def call @passed = @blk.call @failed = !@passed # http://toolmantim.com/thoughts/bangbang_your_nil_is_dead # @passed = !!@blk.call end def passed?; @passed; end def failed?; @failed; end def to_s result = "" pass_fail = { true => 'PASSED', false => 'FAILED'} result << "#{pass_fail[@passed]}" result << "\n #{@msg}" unless @msg.nil? result end end class Assertions < Array def passed_count find_all { |a| a.passed? }.length end def failed_count find_all { |a| a.failed? }.length end def call_all each { |a| a.call } end def inspect collect.with_index { |assertion, i| " #{i+1}) #{assertion.to_s}" } end alias to_s inspect end end class TestEnvironment class << self def test_instance_of(obj, *args, &blk) raise(ArgumentError, 'a block is required') unless block_given? instance_of_obj = obj.new(*args) instance_of_self = new(instance_of_obj) instance_of_self.instance_exec(instance_of_obj, &blk) puts "", "=" * 80, "" puts "Testing an instance of #{obj}:" instance_of_self.run_setups instance_of_self.assertions.call_all puts instance_of_self.assertions.to_s puts "", "=" * 80, "" puts "Assertions: #{instance_of_self.assertions.count}" puts "Passed: #{instance_of_self.assertions.passed_count}" puts "Failed: #{instance_of_self.assertions.failed_count}" end end attr :assertions def initialize(obj) @obj, @setups = obj, [] @assertions = Assertions.new end def setup(&blk) raise(ArgumentError, 'a block is required') unless block_given? @setups << blk end def run_setups #===--- One instance_exec # @obj.instance_exec(@setups) do |setups| # setups.each { |s| s.call } # end #===--- Multi instance_exec @setups.each do |setup| # @obj.instance_eval(&setup) # Shouldnt it be this? @obj.instance_exec(&setup) end end def assert(msg=nil, &blk) raise(ArgumentError, 'a block is required') unless block_given? @assertions << Assertion.new(msg, blk) end end