A little-known and very useful feature Rails brings to the table in terms of testing is a pair of callback hooks for Test::Unit::TestCase setup and teardown.
The callback chains were introduced as part of the move toward a custom ActiveSupport::TestCase, but all the functionality of ActiveSupport::TestCase is exposed to Test::Unit::TestCase if you’re running Rails.
Having these hooks exposed allows you to inject setup and teardown behavior without stepping on the toes of any individual test.
class Test::Unit::TestCase def self.does_not_perform_validations klass setup do @preserved_validations = klass.validate.clone klass.validate.clear end teardown do @preserved_validations.each do |validation| klass.validate << validation end end end end
Obviously this example is a little contrived, but perhaps you see how this can be used.
class MarshmallowTest < Test::Unit::TestCase does_not_perform_validations Marshmallow … end
Now with a single macro, we can inject setup and teardown behavior for a model. The same technique can be used to inject teardown hooks from within individual tests, but beware, hooks injected in this way need to remove themselves from the callback chain when executing, or else they’ll be executed for every subsequent test teardown.
Leave a Comment