简体   繁体   English

Rails-如何为整个测试套件添加方法?

[英]Rails - How to stub a method for the whole test suite?

Right now I'm in the middle of a refactoring and I'm struggling with the following. 现在,我正处于重构过程中,并且我正在努力解决以下问题。

I have a class like this: 我有这样的课:

class Example
  def self.some_method
    if Rails.env.test?
      true
    else
      hit_external_service
    end
  end
 end

Now, I think mixing production code with test code into the class is not very good. 现在,我认为将生产代码与测试代码混合到类中不是很好。 We're using mocha, so I thought of removing the conditional logic and setting up a stub for the whole test suite, since this method gets called all over the place, like this: 我们使用的是mocha,因此我想到了删除条件逻辑并为整个测试套件设置存根,因为这种方法在各处都被调用,如下所示:

class ActiveSupport::TestCase
  setup do
    Example.stub(:some_method).returns(true)
  end
end

But then when I want to test the original method I have to "unstub" it which seems very dirty as well, so I'm kind of stuck on how to do this. 但是,当我想测试原始方法时,我也必须“解开”它,这似乎也很脏,因此我对如何执行此操作有些困惑。

I also thought of extracting the logic of hitting the external service to another class and then having that class as an injectable dependency, so for the whole test suite I could do: 我还想到了提取将外部服务连接到另一个类,然后将该类作为可注入依赖项的逻辑,因此对于整个测试套件,我可以这样做:

Example.external_service = DummyImplementation

and then for the real tests I could do: 然后对于真正的测试,我可以做:

Example.external_service = RealImplementation

but this seems like overkill since the logic is only like 3 lines really. 但这似乎有点过分,因为逻辑实际上只有3行。

So any suggestions? 有什么建议吗? is there something simple that maybe I'm not seeing? 有没有可能我看不到的简单东西?

For stubbing class methods, I usually create the stub in my specific test case that needs it, but then unstub the method on teardown. 对于存根类方法,我通常在需要它的特定测试用例中创建存根,然后在拆卸时取消存根。 Like this: 像这样:

require 'test_helper' 需要'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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM