Ruby-on-rails 如何指定私有方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4154409/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to spec a private method
提问by Mike
I got a model with a private method I'd like to spec with RSpec,
how do you usually do ?
Do you only test the method calling the private one ?
or also spec the private one ? if so, how do you do ?
我有一个带有私有方法的模型,我想用 RSpec 进行规范,
你通常怎么做?你只测试调用私有方法的方法吗?
或者也指定私人的?如果是这样,你怎么做?
回答by Ariejan
I always take this approach: I want to test the public API my class exposes.
我总是采用这种方法:我想测试我的类公开的公共 API。
If you have private methods, you only call them from the public methods you expose to other classes. Hence, if you test that those public methods work as expected under all conditions, you have also proven that the private methods they use work as well.
如果您有私有方法,则只能从公开给其他类的公共方法中调用它们。因此,如果您测试这些公共方法在所有条件下都按预期工作,那么您还证明了它们使用的私有方法也能正常工作。
I'll admit that I've come across some especially complex private methods. In that extreme case you want to test them, you can do this:
我承认我遇到过一些特别复杂的私有方法。在你想测试它们的极端情况下,你可以这样做:
@obj.send(:private_method)
回答by barelyknown
For the private methods that need code coverage (either temporarily or permanently), use the rspec-context-private gemto temporarily make private methods public within a context.
对于需要代码覆盖(临时或永久)的私有方法,使用rspec-context-private gem在上下文中临时公开私有方法。
gem 'rspec-context-private'
It works by adding a shared context to your project.
它的工作原理是向您的项目添加共享上下文。
RSpec.shared_context 'private', private: true do
before :all do
described_class.class_eval do
@original_private_instance_methods = private_instance_methods
public *@original_private_instance_methods
end
end
after :all do
described_class.class_eval do
private *@original_private_instance_methods
end
end
end
Then, if you pass :privateas metadata to a describeblock, the private methods will be public within that context.
然后,如果您将:private元数据作为元数据传递给describe块,则私有方法将在该上下文中公开。
class Example
private def foo
'bar'
end
end
describe Example, :private do
it 'can test private methods' do
expect(subject.foo).not eq 'bar'
end
end
回答by Nathan Crause
If you're wanting to test an expectation on a private method, the accepted answer won't really work (at least not that I know of, so I'm open to correction on that point). What I've done instead is even filthier - in the test itself, just expose the method by redefining it:
如果您想测试对私有方法的期望,那么接受的答案将不会真正起作用(至少不是我所知道的,所以我愿意在这一点上进行更正)。我所做的甚至更脏 - 在测试本身中,只需通过重新定义方法来公开它:
def object_to_test.my_private_method
super
end
Works on Ruby 1.8, can't comment on any of the newer runtimes.
适用于 Ruby 1.8,无法评论任何较新的运行时。

