Created
April 6, 2011 02:46
-
-
Save malclocke/905037 to your computer and use it in GitHub Desktop.
Variation on Rails assert_difference with multiple count values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Runs assert_difference with a number of conditions and varying difference | |
# counts. | |
# | |
# Call as follows: | |
# | |
# assert_differences([['Model1.count', 2], ['Model2.count', 3]]) | |
# | |
def assert_differences(expression_array, message = nil, &block) | |
b = block.send(:binding) | |
before = expression_array.map { |expr| eval(expr[0], b) } | |
yield | |
expression_array.each_with_index do |pair, i| | |
e = pair[0] | |
difference = pair[1] | |
error = "#{e.inspect} didn't change by #{difference}" | |
error = "#{message}\n#{error}" if message | |
assert_equal(before[i] + difference, eval(e, b), error) | |
end | |
end |
An easier way to do this, today, probably due to changes in recent versions of assert_difference
:
structs = {
'Profile.count' => 1,
'Account.count' => 1,
'Transaction.count' => 4,
'Payment.count' => 3
}
assert_difference structs do
action!
end
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
From many years in the future, here's a version that takes Procs too: