Rails

Method/Assertion For Asserting Changes To Add To Your Minitest Arsenal

Posted by Weston Ganger on December 13, 2016

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

Posted in Rails and Tagged with minitest rails testing 


Need help on your next project or application?

I specialize in Ruby-on-Rails, AngularJS, Javascript, Bootstrap, and Hybrid Mobile Apps with Cordova & Ionic.

Contact Me

Recommended Posts