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
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.
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.