:jasonrudolph => :blog

puts Blog.new(”nonsense”)

Evan Phoenix on Testing Private Methods in Ruby

Posted by Jason Rudolph on November 2nd, 2007

At RubyConf today, Stuart Halloway’s Refactotum workshop led to a brief but excellent discussion on the various approaches for testing private methods in Ruby. Ideas ranged from the typical solution of using #send (which won’t work once Ruby 1.9 lands) to Ryan Davis’s technique of simply making everything public. Evan Phoenix, on the other hand, suggested a solution that avoids the soon-to-be-brokeness of using #send while still allowing you to benefit from the inherent intent expressed by defining a method as private.

To demonstrate, let’s assume we have the following (admittedly contrived) class:

  1. class Ninja
  2.   private
  3.     def kill(num_victims)
  4.       "#{num_victims} victims are no longer with us."
  5.     end
  6. end

 
So how can we make sure that the private method is doing what we want, and do so while testing it in isolation? Why not temporarily define a new public method that simply passes through to our elusive private method?

  1. require ‘test/unit’
  2.  
  3. class NinjaTest < Test::Unit::TestCase
  4.   def test_should_punish_sloppy_coders
  5.     @ninja = Ninja.new
  6.     def @ninja.flog_publicly(*args)
  7.       kill(*args)
  8.     end
  9.     assert_equal ‘3 victims are no longer with us.’, @ninja.flog_publicly(3)
  10.   end
  11. end

 
Sweet!

  1. src> ruby ninja.rb
  2. Loaded suite ninja
  3. Started
  4. .
  5. Finished in 0.000274 seconds.
  6.  
  7. 1 tests, 1 assertions, 0 failures, 0 errors

 

Print This Post Print This Post

3 Responses to “Evan Phoenix on Testing Private Methods in Ruby”

  1. Fred Says:

    Good Blog J. Rudy.

    I manage to take a peek every week.

  2. Como testar um método privado? Says:

    […] esta dica no blog do Jason Rudolph, mas ele mesmo ouvi isto do Evan Phoenix no RubyConf no ano passado. Durante uma discussão sobre […]

  3. Como testar um método privado? Says:

    […] esta dica no blog do Jason Rudolph, mas ele mesmo ouvi isto do Evan Phoenix no RubyConf no ano passado. Durante uma discussão sobre […]