views:

332

answers:

3

I have a private method in my controller. which is used for some database update. this method i am calling from another controller method. and it works fine.

But when i am trying to write a test case for that method then It is tripping on accessing (session variable and params) in my functional all other methods are working fine the problem is only with private method?

In my setup method in functional test, I am setting session also.?

A: 

How about testing against a subclass that makes your private (protected) method accessible via a wrapping method?

class Controller

protected
  def your_private_method
    ...
  end

end


class SubclassForTest < Controller

  def testwrapper
    your_private_method
  end

end
Dennis
The idea is good, but subclassing is dangerous because of the metaprogramming that Rubyists use -- class names will change. This is particularly messy with Rails.
James A. Rosen
+3  A: 

You should avoid testing private methods. The "goal" behind having public/private/protected methods is to encapsulate logic and make it easy to change parts of your code without having to worry about how one function or class interacts with another.

That being said, if you still feel the need to test your private methods, there are work arounds. I found this utility function via Jay Field's blog:

class Class
  def publicize_methods
    saved_private_instance_methods = self.private_instance_methods
    self.class_eval { public *saved_private_instance_methods }
    yield
    self.class_eval { private *saved_private_instance_methods }
  end
end

Check the link for usage details, seems like a quick and simple way to do what you're looking to do.

Damien Wilson
+1  A: 

I like Damien Wilson's suggestion. I second his statement that you, "should avoid testing private methods." When necessary, I declare a public version of the method:

class FooTest < Test::Unit::TestCase
  Foo.class_eval do
    def public_bar(*args, &block)
      private_bar(*args, &block)
    end
  end

  def test_bar
    assert_equal 42, Foo.new.public_bar
  end
end
James A. Rosen