Froze rails gems
[depot.git] / vendor / rails / activesupport / lib / active_support / testing / core_ext / test / unit / assertions.rb
1 require 'test/unit/assertions'
2 module Test
3 module Unit
4 #--
5 # FIXME: no Proc#binding in Ruby 2, must change this API
6 #++
7 module Assertions
8 # Test numeric difference between the return value of an expression as a result of what is evaluated
9 # in the yielded block.
10 #
11 # assert_difference 'Article.count' do
12 # post :create, :article => {...}
13 # end
14 #
15 # An arbitrary expression is passed in and evaluated.
16 #
17 # assert_difference 'assigns(:article).comments(:reload).size' do
18 # post :create, :comment => {...}
19 # end
20 #
21 # An arbitrary positive or negative difference can be specified. The default is +1.
22 #
23 # assert_difference 'Article.count', -1 do
24 # post :delete, :id => ...
25 # end
26 #
27 # An array of expressions can also be passed in and evaluated.
28 #
29 # assert_difference [ 'Article.count', 'Post.count' ], +2 do
30 # post :create, :article => {...}
31 # end
32 #
33 # A error message can be specified.
34 #
35 # assert_difference 'Article.count', -1, "An Article should be destroyed" do
36 # post :delete, :id => ...
37 # end
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))
42 end]
43 end
44
45 original_values = expression_evaluations.inject([]) { |memo, expression| memo << expression[1].call }
46 yield
47 expression_evaluations.each_with_index do |expression, i|
48 full_message = ""
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
52 end
53 end
54
55 # Assertion that the numeric result of evaluating an expression is not changed before and after
56 # invoking the passed in block.
57 #
58 # assert_no_difference 'Article.count' do
59 # post :create, :article => invalid_attributes
60 # end
61 #
62 # A error message can be specified.
63 #
64 # assert_no_difference 'Article.count', "An Article should not be destroyed" do
65 # post :create, :article => invalid_attributes
66 # end
67 def assert_no_difference(expressions, message = nil, &block)
68 assert_difference expressions, 0, message, &block
69 end
70 end
71 end
72 end