Rails Rspec - 如何测试Service是否在另一个Service中被调用

Rails Rspec - How to test if Service has been called in another Service

在编写测试时,我停止尝试在另一个服务中测试服务。在这种情况下,我可能应该只检查 Service 是否已被调用,因为它已经在其他地方进行过测试。我在 Internet 上做了一些研究,发现了类似 have_received 的东西,但我不知道如何在我的示例中使用它。

check_service.rb

Class CheckService
 def initialize(params)
   @params = params
 end

 def self.call(params)
   new(params).call
 end

 def call
   CheckUser.call(params[:user_id])
 end
end

check_service_spec.rb

...

describe 'call' do
 let(:result) { CheckService.call(params) }
 let(:params) { { user_id: "100" } }
 let(:check_user) { instance_double(CheckUser) }

 before do
   allow(check_user).to receive(:call).and_return(true)
 end

 it do 
  result
  expect(check_user).to have_received(:call) 
 end
end
...

我正在尝试这样的事情(这是一个简单的例子),但我得到了错误:

(InstanceDouble(CheckUser) (anonymous)).call(*(any args))
           expected: 1 time with any arguments
           received: 0 times with any arguments

是否有任何选项可以测试我提供的情况?

简答

describe 'call' do
 let(:result) { CheckService.call(params) }
 let(:params) { { user_id: "100" } }
 ## let(:check_user) { instance_double(CheckUser) } delete this

 before do
   allow(CheckUser).to receive(:call).and_return(true)
 end

 it do 
  result
  expect(CheckUser).to have_received(:call) 
 end
end

备选

我认为更好的测试方法是使用 DI(依赖注入),因此您将 CheckUser 作为依赖项传递给 CheckService。我也更喜欢在 it 块中编写整个测试!

class CheckService
  def initialize(params, check_handler:)
    @params = params
    @check_handler = check_handler
  end

  def self.call(params, check_handler: CheckUser)
    new(params, check_handler: check_handler).call
  end

  def call
    @check_handler.call(@params[:user_id])
  end
end
describe 'call' do
  it 'check user with params' do
    check_user = class_double(CheckUser)
    allow(check_user).to receive(:call).and_return(true)

    params = { user_id: "100" }
    CheckService.call(params, check_handler: check_user)

    expect(check_user).to have_received(:call)
  end
end

一个博客 post 阅读更多 -> https://blog.testdouble.com/posts/2018-05-17-do-we-need-dependency-injection-in-ruby/