Ruby-on-rails RSpec:存根私有方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14987141/
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
RSpec: Stub private method
提问by 23tux
I try to test a class with RSpec2, that has some private methods, which are called from some public methods. I test the public methods with
我尝试使用 RSpec2 测试一个类,该类具有一些从一些公共方法调用的私有方法。我测试公共方法
@foo.should_receive(:start_training).exactly(2).times
if they are called and how often. My problem is, that this approach doesn't work with private methods. So, is there any way to use sth like @foo.send(:private_method)in combination with should_receive? Or any other syntax?
如果他们被调用以及多久调用一次。我的问题是,这种方法不适用于私有方法。那么,有没有办法将 sth like@foo.send(:private_method)与 结合使用should_receive?或者任何其他语法?
回答by Justin Aiken
should_receive(:method)works whether the visibility of :methodis public or private.
should_receive(:method)无论 的可见性:method是公开的还是私有的。
回答by Sinscary
You can use allow_any_instance_ofmethod to stub or mock any instance of a class
for e.g. you have a classnamed Foowith some privatemethods than you can do something like this
您可以使用allow_any_instance_of方法来存根或模拟类的任何实例,例如,您有一个使用某些方法class命名的方法,而您可以执行这样的操作Fooprivate
allow_any_instance_of(Foo).to receive(:private_method) do
#do something
end
In case if there you have modulealso, you can do something like this
如果你module也有,你可以做这样的事情
allow_any_instance_of(Module::Foo).to receive(:private_method) do
#do something
end
You can find more details about allow_any_instance_of()method at Official Documentation
您可以allow_any_instance_of()在官方文档中找到有关方法的更多详细信息
回答by Richard Brown
Why do you want to test the private methods? They're private for a reason; to prevent access from external calls. Testing the public methods that rely on the private methods should be sufficient.
为什么要测试私有方法?他们是私人的是有原因的;以防止来自外部呼叫的访问。测试依赖于私有方法的公共方法就足够了。
回答by Unkas
the bad news is: you can not stub private method
坏消息是:你不能存根私有方法
the good one is: you can make your method protectedand then stub it the usual way
好的一点是:你可以制作你的方法protected,然后以通常的方式存根
allow_any_instance_of(described_class).to receive(:my_protected_method_name).and_return("foo_bar")
allow_any_instance_of(described_class).to receive(:my_protected_method_name).and_return("foo_bar")

