1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

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 # end
def assert_difference(expressions, difference = 1, message = nil, &block) def assert_difference(expressions, difference = 1, message = nil, &block)
expression_evaluations = Array(expressions).map do |expression| expression_evaluations = Array(expressions).map do |expression|
lambda do [expression, lambda do
eval(expression, block.__send__(:binding)) eval(expression, block.__send__(:binding))
end 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 yield
expression_evaluations.each_with_index do |expression, i| 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
end end

View file

@ -60,6 +60,24 @@ class AssertDifferenceTest < Test::Unit::TestCase
@object.increment @object.increment
end end
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 else
def default_test; end def default_test; end
end end