From: Intransition Date: 2010-11-05T03:56:21+09:00 Subject: Re: true! or false! On Nov 4, 1:31 pm, Josh Cheek wrote: > On Thu, Nov 4, 2010 at 5:55 AM, Intransition wrote: > > Making good use of polymorphism I had this idea for assertion methods: > > >  class TrueClass > >    # Assert true. > >    # > >    #   (x == y).true! > >    # > >    def true! > >      true > >    end > >    # Assert false. > >    # > >    #   (x == y).false! > >    # > >    def false! > >      raise "not false!" > >    end > >  end > > >  class FalseClass > >    # Assert true. > >    # > >    #   (x == y).true! > >    # > >    def true! > >      raise "not true!" > >    end > >    # Assert false. > >    # > >    #   (x == y).false! > >    # > >    def false! > >      true > >    end > >  end > > > If only the error message could say something about WHAT was not true > > or false, this could be pretty nifty. > > You would need to override at a higher level, I think, because I frequently > use object/nil instead of true/false. Could add the methods to NilClass too. > require 'test/unit' > > class Object >   def true!   ;  self || raise("not true!")   ;  end >   def false!  ;  self && raise("not false!")  ;  end > end Hmm... Yes, that might be better b/c then anything other then false and nil will evaluate as true too. That is a good thing, right? > class TrueBangFalseBang < Test::Unit::TestCase >   def test_object       ;  [1,2,3][2].true!   ;  end >   def test_non_object   ;  [1,2,3][3].false!  ;  end >   def test_true         ;  (1==1).true!       ;  end >   def test_false        ;  (1==2).false!      ;  end > end > > I like it, except that it doesn't count these as assertions. Even if you mix > the assertions module into object and use the assert methods, like this: > > class Object >   include Test::Unit::Assertions >   def true!   ;  assert self   ;  end >   def false!  ;  assert !self  ;  end > end > > You would get results like "4 tests, 0 assertions, 2 failures", maybe if you > look even further under the hood you could figure out how to get them to > count. Or just choose to not care, but for me, that is a number I like to > see :) Yes, that's possible but it depends on which test framework you are using. For MiniTest, for instance, it would probably be something like: MiniTest::Assertions._assertions+=1 raise MiniTest::Assertion.new(err) Too bad there isn't some sort of core support for this kind of thing that could be used across test frameworks.