Testing private class methods in Ruby

I generally make a point of not unit testing private methods however in some circumstance I find it necessary to do so. One example of this is when a class method is to be documented in the API of a library, only for use when declaring a descendent class (the Rails validates_* macros could be private for example).

Testing of private instance methods has already been documented by Jay Fields, however testing private class methods requires a little more work:


class Class
  def publicize_private_class_methods
    saved_instance_methods = (class << self; private_instance_methods.sort; end)
    saved_instance_methods.each { |method| public_class_method method }
    yield self
  ensure
    saved_instance_methods.each { |method| private_class_method method }
  end
end

This allows you to do the following:


class Foo
  class << self
    private

    def foo
      'bar'
    end
  end
end

Foo.publicize_private_class_methods do |klass|
  assert_equal 'bar', klass.foo
end

The same would work for protected methods by changing all instances of the word ‘private’ with ‘protected’.

All this could probably be merged into the original method by Jay, however I will leave that as an exercise for the reader.