Friday, May 4, 2007

assert_changes

Update: I have a patch awaiting approval on test-spec to add should.differ, change, increase and decrease. These read a lot better than the assert_difference/change methods.
# Checks multiple methods on object before and after the block asserting that there is
# a different value returned for each method. This is especially good for non-numeric fields.
def assert_changes(object, methods = nil)
  methods = [methods] unless methods.is_a? Array

  initial_values = {}
  for method in methods
    initial_values[method] = object.send(method)
  end


  yield
  object.reload if object.respond_to? :reload


  for method in methods
    assert_not_equal initial_values[method], object.send(method), "#{object}##{method}"
  end
end

alias assert_change assert_changes