From 689b529ea82b2375ee3f743eb82da9b83e0d00ff Mon Sep 17 00:00:00 2001 From: Marcel Molina Date: Tue, 8 May 2007 03:54:34 +0000 Subject: Simplify API of assert_difference by passing in an expression that is evaluated before and after the passed in block. See documenation for examples of new API. [Marcel Molina Jr.] git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@6693 5ecf4fe2-1ee6-0310-87b1-e25e094e27de --- .../lib/active_support/core_ext/test/difference.rb | 51 +++++++++++++--------- 1 file changed, 31 insertions(+), 20 deletions(-) (limited to 'activesupport/lib/active_support/core_ext/test') diff --git a/activesupport/lib/active_support/core_ext/test/difference.rb b/activesupport/lib/active_support/core_ext/test/difference.rb index 1f85f0f4b7..65dae3469b 100644 --- a/activesupport/lib/active_support/core_ext/test/difference.rb +++ b/activesupport/lib/active_support/core_ext/test/difference.rb @@ -1,29 +1,40 @@ - module Test #:nodoc: module Unit #:nodoc: - class TestCase #:nodoc: - - # Test difference between the return value of method on object for duration of the block - def assert_difference(objects, method = nil, difference = 1) - objects = [objects].flatten - initial_values = objects.inject([]) { |sum,obj| sum << obj.send(method) } + class TestCase #:nodoc: + # Test numeric difference between the return value of an expression as a result of what is evaluated + # in the yielded block. + # + # assert_difference 'Post.count' do + # post :create, :post => {...} + # end + # + # An arbitrary expression is passed in an evaluated. + # + # assert_difference 'assigns(:post).comments(:reload).size' do + # post :create, :comment => {...} + # end + # + # An arbitrary positive or negative difference can be specified. The default is 1. + # + # assert_difference 'Post.count', -1 do + # post :delete, :id => ... + # end + def assert_difference(expression, difference = 1, &block) + expression_evaluation = lambda { eval(expression) } + original_value = expression_evaluation.call yield - if difference.nil? - objects.each_with_index { |obj,i| - assert_not_equal initial_values[i], obj.send(method), "#{obj}##{method}" - } - else - objects.each_with_index { |obj,i| - assert_equal initial_values[i] + difference, obj.send(method), "#{obj}##{method}" - } - end + assert_equal original_value + difference, expression_evaluation.call end - # Test absence of difference between the return value of method on object for duration of the block - def assert_no_difference(objects, method = nil, &block) - assert_difference objects, method, 0, &block + # Assertion that the numeric result of evaluating an expression is not changed before and after + # invoking the passed in block. + # + # assert_no_difference 'Post.count' do + # post :create, :post => invalid_attributes + # end + def assert_no_difference(expression, &block) + assert_difference expression, 0, &block end - end end end -- cgit v1.2.3