Rails 控制器私有方法的功能测试
我的控制器中有一个私有方法。用于某些数据库更新。我从另一个控制器方法调用这个方法。而且效果很好。
但是,当我尝试为该方法编写测试用例时,它在我的功能中访问(会话变量和参数)时出错,所有其他方法都工作正常,问题仅在于私有方法吗?
在功能测试的设置方法中,我也在设置会话。?
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.?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该避免测试私有方法。拥有公共/私有/受保护方法背后的“目标”是封装逻辑并使更改部分代码变得容易,而不必担心一个函数或类如何与另一个函数或类交互。
话虽这么说,如果您仍然觉得需要测试您的私有方法,还有一些解决方法。我通过 Jay Field 的博客找到了这个实用函数:
检查链接以获取使用详细信息,这似乎是一种快速而简单的方法来完成您想要做的事情。
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:
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:
如何针对子类进行测试,使您的私有(受保护)方法可以通过包装方法进行访问?
How about testing against a subclass that makes your private (protected) method accessible via a wrapping method?