简体   繁体   English

Rspec,如何测试多个服务调用的方法?

[英]Rspec, how to test method with multiple service calls?

Class structure: Class 结构:

class Service1
  def foo
    puts 'foo'
  end
end

class Service2
  def bar
    3.times.each do 
      Service1.new().foo
    end
  end
end

I want to test that bar method of Service2 is called 3 times.我想测试一下Service2bar方法被调用了 3 次。

How to do it best in rspec3?如何在 rspec3 中做到最好?

I would refactor the code to:我会将代码重构为:

class Service1
  def self.foo
    new.foo
  end

  def foo
    puts 'foo'
  end
end

class Service2
  def bar
    3.times.each do 
      Service1.foo
    end
  end
end

And would then use a spec like this然后会使用这样的规范

describe "#bar" do
  let(:service1) { class_double("Service1") }

  it "calls Service1.foo three times" do
    expect(service1).to receive(:foo).exactly(3).times

    Service2.bar
  end
end

You can achieve this by mocking new method您可以通过 mocking new方法来实现这一点

class Service1
  def foo
    puts 'foo'
  end
end

class Service2
  def bar
    3.times.each do 
      Service1.new().foo
    end
  end
end

Then the test:然后测试:

let(:mocked_service) { instance_spy Service1 }

it "calls Service1.foo three times" do
  allow(Service1).to receive(:new).and_return mocked_service

  Service2.bar

  expect(mocked_service).to have_received(:foo).exactly(3).times
end

However, as mentioned in the comment - the necessity of using mocks is a first sign of flawed OO design, meaning that the problem you posted is merely a symptom.但是,正如评论中所提到的 - 使用模拟的必要性是有缺陷的 OO 设计的第一个迹象,这意味着您发布的问题只是一个症状。 Refer to SOLID principles to find better design.请参阅 SOLID 原则以找到更好的设计。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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