Aliasing dangerous methods in your tests

Manfred Stienstra

Lately we’ve been aliasing dangerous methods in our tests to make sure we don’t accidentally break something. It’s not very nice when tests delete your favorite episode of Sesame Street or add a MySQL user, so we had a lot of snippets like this laying around:

module Kernel
  mattr_accessor :allow_system
  self.allow_system = false

  alias original_system system

  def self.system(*args)
    if allow_system
      original_system(*args)
    else
      raise RuntimeError, "You're trying to do a system call, which is probably not a very good idea in a test."
    end
  end
end

We refactored it and now we specify the same thing like this:

ActiveResource::Connection.add_allow_switch :request
Kernel.add_allow_switch :system, :default => true

The code is currently included in on_test_spec, our plugin for writing Rails specs on test/spec.


You’re reading an archived weblog post that was originally published on our website.