Assert All lines

Hi,
I’m trying to create a method to assert all lines and if any of them
fail then the whole block will fail
require ‘test/unit’

def assert_all(message="assert_block failed.") # :yields:
    _wrap_assertion do
      if (!yield)
        puts "ERROR"
        raise Test::Unit::AssertionFailedError.new(message.to_s)
      else
        puts "PERFECT"
      end
    end
  end

class MyTest < Test::Unit::TestCase
def test01
assert_all {
1==1
2==3
3==3
}
end
end

But it seems like it is not giving an error in this case

You could AND them together. 1==1 and 2==3 and 3==3 => false

On 7 September 2012 22:43, Mario R. [email protected] wrote:

      else
  3==3
}

end
end

But it seems like it is not giving an error in this case


Posted via http://www.ruby-forum.com/.


Matthew K., B.Sc (CompSci) (Hons)
http://matthew.kerwin.net.au/
ABN: 59-013-727-651

“You’ll never find a programming language that frees
you from the burden of clarifying your ideas.” - xkcd

Mario R. wrote in post #1075041:

assert_all {
  1==1
  2==3
  3==3
}

If you really want what you’ve written then you’ll need something like
ParseTree to extract the individual expressions and assert them
individually.

But you could just do:

assert 1==1
assert 2==2
assert 3==3

or:

assert(1==1
&& 2==2
&& 3==3)

In both cases these will “fail fast”, i.e. as soon as one expression
fails no more will be tried. If you want to run all three regardless,
then you’ll need some sort of flag to say that one of them failed, and
test that at the end.

On Sep 7, 2012, at 05:43 , Mario R. [email protected] wrote:

     else
 3==3

}
end
end

Switch {} to () and add commas:

def assert_all(message, *exprs)
exprs.each_with_index do |expr, i|
assert expr, “Failed on #{i+1}: #{message}”
end
end

I know you’re trying to make this as succinct and clean as possible, but
there is no way to individually evaluate each expression w/o some
seriously heinous “magic”. This alternative tries to balance out the
magic vs the syntax.

I also removed the optional message argument for a mandatory one so you
don’t have to try to distinguish between a message and the first
assertion. The alternative to that is to pass in a hash with expr =>
message, but that starts to get gross too.

Thanks Ryan it works perfectly for me :slight_smile:

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs