![](/img/trans.png)
[英]How to stub/mock a helper method for functional test in Rails 2.3?
[英]Rails - How to stub a method for the whole test suite?
现在,我正处于重构过程中,并且我正在努力解决以下问题。
我有这样的课:
class Example
def self.some_method
if Rails.env.test?
true
else
hit_external_service
end
end
end
现在,我认为将生产代码与测试代码混合到类中不是很好。 我们使用的是mocha,因此我想到了删除条件逻辑并为整个测试套件设置存根,因为这种方法在各处都被调用,如下所示:
class ActiveSupport::TestCase
setup do
Example.stub(:some_method).returns(true)
end
end
但是,当我想测试原始方法时,我也必须“解开”它,这似乎也很脏,因此我对如何执行此操作有些困惑。
我还想到了提取将外部服务连接到另一个类,然后将该类作为可注入依赖项的逻辑,因此对于整个测试套件,我可以这样做:
Example.external_service = DummyImplementation
然后对于真正的测试,我可以做:
Example.external_service = RealImplementation
但这似乎有点过分,因为逻辑实际上只有3行。
有什么建议吗? 有没有可能我看不到的简单东西?
对于存根类方法,我通常在需要它的特定测试用例中创建存根,然后在拆卸时取消存根。 像这样:
需要'test_helper'
class MyTest < ActiveSupport::TestCase
def teardown
Example.unstub(:some_method)
end
test "not hitting the service" do
Example.stub(:some_method).returns(true)
assert Example.some_method
end
test "hitting the service" do
assert Example.some_method
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.