I was surprised to see that Minitest does not offer an assert_changed
and assert_not_changed
method by default. Rails has a similar method to this called assert_difference but it does a different job. Here are two ways you can add this to your test suite.
One way to add it, is to get it using my gem rearmed which is a collection of helpful monkey patches for Rails and Ruby that are safely applied on opt-in basis.
Or if you don’t use that gem just add this to your test helpers:
# test_helper.rb
def assert_changed(expression, &block)
if expression.respond_to?(:call)
e = expression
else
e = lambda{ block.binding.eval(expression) }
end
old = e.call
block.call
refute_equal old, e.call
end
def assert_not_changed(expression, &block)
if expression.respond_to?(:call)
e = expression
else
e = lambda{ block.binding.eval(expression) }
end
old = e.call
block.call
assert_equal old, e.call
end
You can then use these methods in your tests like so:
@str = 'test'
assert_changed '@str' do
@str = 'foobar'
end
assert_not_changed '@str' do
@str = false
end