Posted By


ctran on 08/14/06

Tagged


Statistics


Viewed 378 times
Favorited by 1 user(s)

Related snippets


assert_difference


/ Published in: Ruby
Save to your folder(s)

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


Copy this code and paste it in your HTML
  1. module AssertHelper
  2. # Author:: http://blog.caboo.se/articles/2006/06/13/a-better-assert_difference
  3. #
  4. # == Examples
  5. # assert_difference Group, :count do
  6. # post :create, :group => { :name => 'monkeys' }
  7. # end
  8. #
  9. # assert_difference [ User, Group ], :count do
  10. # Membership.create(:user_id => 1, :group_id => 5)
  11. # end
  12. #
  13. # assert_difference User, :name, nil do
  14. # post :update, :id => 5, { :name => 'monkeys' }
  15. # end
  16. def assert_difference(objects, method = nil, difference = 1)
  17. objects = [objects].flatten
  18. initial_values = objects.inject([]) { |sum,obj| sum << obj.send(method) }
  19. yield
  20. if difference.nil?
  21. objects.each_with_index { |obj,i|
  22. assert_not_equal initial_values[i], obj.send(method), "#{obj}##{method}"
  23. }
  24. else
  25. objects.each_with_index { |obj,i|
  26. assert_equal initial_values[i] + difference, obj.send(method), "#{obj}##{method}"
  27. }
  28. end
  29. end
  30.  
  31. def assert_no_difference_in_size(object, methods = nil, &block)
  32. assert_difference_in_size object, methods, 0, &block
  33. end
  34. end

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.