Skip to content

Instantly share code, notes, and snippets.

@malclocke
Created April 6, 2011 02:46
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save malclocke/905037 to your computer and use it in GitHub Desktop.
Save malclocke/905037 to your computer and use it in GitHub Desktop.
Variation on Rails assert_difference with multiple count values
# 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
@alexmdavis
Copy link

From many years in the future, here's a version that takes Procs too:

# Runs assert_difference with a number of conditions and varying difference
# counts.
#
# Call as follows:
#
# assert_differences([['Model1.count', 2], ['Model2.count', 3]])
# or
# assert_differences([[->{Model1.count}, 2], [->{Model2.count}, 3]])
#
# The array can freely mix the String and Proc forms.
#
def assert_differences(expression_array, message = nil, &block)
  def result(expr, b)
    expr.is_a?(String) ? eval(expr, b) : expr.call
  end

  b = block.send(:binding)
  before = expression_array.map { |expr| result(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, result(e, b), error)
  end
end

@LucasArruda
Copy link

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