Return to Snippet

Revision: 839
at August 14, 2006 11:27 by ctran


Initial Code
module AssertHelper
  # Author:: http://blog.caboo.se/articles/2006/06/13/a-better-assert_difference
  # 
  # == Examples
  #   assert_difference Group, :count do
  #     post :create, :group => { :name => 'monkeys' }
  #   end
  #   
  #   assert_difference [ User, Group ], :count do
  #     Membership.create(:user_id => 1, :group_id => 5)
  #   end 
  #   
  #   assert_difference User, :name, nil do
  #     post :update, :id => 5, { :name => 'monkeys' }
  #   end
  def assert_difference(objects, method = nil, difference = 1)
    objects = [objects].flatten
    initial_values = objects.inject([]) { |sum,obj| sum << obj.send(method) }
    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
  end
  
  def assert_no_difference_in_size(object, methods = nil, &block)
    assert_difference_in_size object, methods, 0, &block
  end
end

Initial URL
http://blog.caboo.se/articles/2006/06/13/a-better-assert_difference

Initial Description
To assert the difference in values before and after some code blocks.  Save this as assert_helper.rb and include it in your test_helper.rb

Initial Title
assert_difference

Initial Tags
rails

Initial Language
Ruby