lib/ruby_ext/must.rb in ruby-ext-0.4.1 vs lib/ruby_ext/must.rb in ruby-ext-0.4.2

- old
+ new

@@ -1,23 +1,37 @@ -class AssertionError < RuntimeError; end +class AssertionError < StandardError; end class MustAssertions < ExtraBlankSlate + attr_reader :obj + def initialize obj @obj = obj end def == o @obj == o end + def =~ o + @obj =~ o + end + def never_called false end def nil @obj.equal? nil end + + def defined + !nil + end + + def respond_to method + @obj.respond_to? method + end def a klass if klass.class == Array klass.any?{|k| @obj.is_a? k} else @@ -36,12 +50,21 @@ def include o @obj.include? o end - def in *enum - Array(enum).include? @obj + def in *args + if args.size == 1 + obj = args.first + if obj.is_a?(Array) or obj.is_a?(Range) + obj.include? @obj + else + args.include? @obj + end + else + args.include? @obj + end end def true !!@obj end @@ -56,18 +79,34 @@ def blank @obj.blank? end + def present + !@obj.blank? + end + def > o @obj > o end def < o @obj < o end + def >= o + @obj >= o + end + + def <= o + @obj <= o + end + + def exist arg + @obj.exist? arg + end + def be @prefix = 'be' self end @@ -85,51 +124,55 @@ def method_missing m, *args, &b raise RuntimeError, "Assertion '#{m}' is unknown!", caller[1..-1] end def failed method, negative, *args + stack = caller.sfilter('must.rb') + unless args.empty? Kernel.raise AssertionError, " - ASSERTION FAILED (#{caller[1]}): - #{@obj.inspect} must #{'not ' if negative}#{"#{@prefix} " if @prefix}#{method} #{args.first} - ", caller[3..-1] + ASSERTION FAILED (#{stack.first}): + #{@obj.inspect} must #{'not ' if negative}#{"#{@prefix} " if @prefix}#{method} #{args.first.inspect} + ", stack else Kernel.raise AssertionError, " - ASSERTION FAILED (#{caller[1]}): + ASSERTION FAILED (#{stack.first}): #{@obj.inspect} must #{'not ' if negative}#{"#{@prefix} " if @prefix}#{method} - ", caller[3..-1] + ", stack end end end class Must < MustAssertions assertions.each do |m| desition = "_#{m}" alias_method desition, m define_method m do |*args| failed m, false, *args unless __send__(desition, *args) + @obj end end end class MustNot < MustAssertions assertions.each do |m| desition = "_#{m}" alias_method desition, m define_method m do |*args| - failed m, true, *args if __send__(desition, *args) + failed m, true, *args if __send__(desition, *args) + @obj end end end Object.class_eval do def must - Must.new self + Must.new(self) end def must_not - MustNot.new self + MustNot.new(self) end def must_be must.be end \ No newline at end of file