module ActiveSupport::Testing::Assertions
def assert_difference(expression, *args, &block)
post :delete, params: { id: ... }
assert_difference 'Article.count', -1, 'An Article should be destroyed' do
An error message can be specified.
end
post :create, params: { article: {...} }
assert_difference [->{ Article.count }, ->{ Post.count }], 2 do
end
post :create, params: { article: {...} }
assert_difference ->{ Article.count }, 2 do
A lambda or a list of lambdas can be passed in and evaluated:
end
post :create, params: { article: {...} }
assert_difference ->{ Article.count } => 1, ->{ Notification.count } => 2 do
A hash of expressions/numeric differences can also be passed in and evaluated.
end
post :create, params: { article: {...} }
assert_difference [ 'Article.count', 'Post.count' ], 2 do
An array of expressions can also be passed in and evaluated.
end
post :delete, params: { id: ... }
assert_difference 'Article.count', -1 do
The default is 1.
An arbitrary positive or negative difference can be specified.
end
post :create, params: { comment: {...} }
assert_difference 'Article.last.comments(:reload).size' do
An arbitrary expression is passed in and evaluated.
end
post :create, params: { article: {...} }
assert_difference 'Article.count' do
result of what is evaluated in the yielded block.
Test numeric difference between the return value of an expression as a
def assert_difference(expression, *args, &block) expressions = if expression.is_a?(Hash) message = args[0] expression else difference = args[0] || 1 message = args[1] Array(expression).index_with(difference) end exps = expressions.keys.map { |e| e.respond_to?(:call) ? e : lambda { eval(e, block.binding) } } before = exps.map(&:call) retval = _assert_nothing_raised_or_warn("assert_difference", &block) expressions.zip(exps, before) do |(code, diff), exp, before_value| error = "#{code.inspect} didn't change by #{diff}" error = "#{message}.\n#{error}" if message assert_equal(before_value + diff, exp.call, error) end retval end