开发者

functional test for rails controller private method

开发者 https://www.devze.com 2022-12-28 17:01 出处:网络
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.

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 开发者_JS百科setting session also.?


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.


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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消