added nicer failure reporting to #assert_difference to tell you the expression that failed rather than just the expected and actual values

Signed-off-by: Michael Koziarski <michael@koziarski.com>
[#1161 state:committed]
This commit is contained in:
madlep 2008-10-03 11:58:28 +10:00 committed by Michael Koziarski
parent 395369bc2b
commit 00e2ba76b2
2 changed files with 25 additions and 4 deletions

View File

@ -37,15 +37,18 @@ module Test
# end
def assert_difference(expressions, difference = 1, message = nil, &block)
expression_evaluations = Array(expressions).map do |expression|
lambda do
[expression, lambda do
eval(expression, block.__send__(:binding))
end
end]
end
original_values = expression_evaluations.inject([]) { |memo, expression| memo << expression.call }
original_values = expression_evaluations.inject([]) { |memo, expression| memo << expression[1].call }
yield
expression_evaluations.each_with_index do |expression, i|
assert_equal original_values[i] + difference, expression.call, message
full_message = ""
full_message << "#{message}.\n" if message
full_message << "<#{expression[0]}> was the expression that failed"
assert_equal original_values[i] + difference, expression[1].call, full_message
end
end

View File

@ -60,6 +60,24 @@ class AssertDifferenceTest < Test::Unit::TestCase
@object.increment
end
end
def test_array_of_expressions_identify_failure
assert_difference ['@object.num', '1 + 1'] do
@object.increment
end
fail 'should not get to here'
rescue Test::Unit::AssertionFailedError => e
assert_equal "<1 + 1> was expression that failed.\n<3> expected but was\n<2>.", e.message
end
def test_array_of_expressions_identify_failure_when_message_provided
assert_difference ['@object.num', '1 + 1'], 1, 'something went wrong' do
@object.increment
end
fail 'should not get to here'
rescue Test::Unit::AssertionFailedError => e
assert_equal "something went wrong.\n<1 + 1> was expression that failed.\n<3> expected but was\n<2>.", e.message
end
else
def default_test; end
end