1 require 'test/unit/assertions'
5 # FIXME: no Proc#binding in Ruby 2, must change this API
8 # Test numeric difference between the return value of an expression as a result of what is evaluated
9 # in the yielded block.
11 # assert_difference 'Article.count' do
12 # post :create, :article => {...}
15 # An arbitrary expression is passed in and evaluated.
17 # assert_difference 'assigns(:article).comments(:reload).size' do
18 # post :create, :comment => {...}
21 # An arbitrary positive or negative difference can be specified. The default is +1.
23 # assert_difference 'Article.count', -1 do
24 # post :delete, :id => ...
27 # An array of expressions can also be passed in and evaluated.
29 # assert_difference [ 'Article.count', 'Post.count' ], +2 do
30 # post :create, :article => {...}
33 # A error message can be specified.
35 # assert_difference 'Article.count', -1, "An Article should be destroyed" do
36 # post :delete, :id => ...
38 def assert_difference(expressions
, difference
= 1, message
= nil, &block
)
39 expression_evaluations
= Array(expressions
).map
do |expression
|
40 [expression
, lambda
do
41 eval(expression
, block
.__send__(:binding))
45 original_values
= expression_evaluations
.inject([]) { |memo
, expression
| memo
<< expression
[1].call
}
47 expression_evaluations
.each_with_index
do |expression
, i
|
49 full_message
<< "#{message}.\n" if message
50 full_message
<< "<#{expression[0]}> was the expression that failed"
51 assert_equal original_values
[i
] + difference
, expression
[1].call
, full_message
55 # Assertion that the numeric result of evaluating an expression is not changed before and after
56 # invoking the passed in block.
58 # assert_no_difference 'Article.count' do
59 # post :create, :article => invalid_attributes
62 # A error message can be specified.
64 # assert_no_difference 'Article.count', "An Article should not be destroyed" do
65 # post :create, :article => invalid_attributes
67 def assert_no_difference(expressions
, message
= nil, &block
)
68 assert_difference expressions
, 0, message
, &block