在测试环境中如何干净地存根REST客户端

时间:2019-03-12 14:03:25

标签: ruby-on-rails unit-testing testing rspec

我有如下基本模型

class MyModel
    def initialize(attrs)   
        @attrs = attrs
        @rest_client = Some::REST::Client.new 
    end

    def do_a_rest_call(some_str)
      @rest_client.create_thing(some_str)
    end
end

出于测试目的,我不希望@rest_client进行远程调用。相反,在测试环境中,我只想确保通过特定代码分支的特定@rest_clientsome_str调用。

在理想的世界中,我有一个类似的断言:

expect(my_model_instance).to.receive(do_a_rest_call).with(some_str)在测试中,我将通过some_str以确保它是正确的。

使用RSpec 3.8和Rails 5.2.2做到这一点的最佳方法是什么?

1 个答案:

答案 0 :(得分:2)

一种无需任何其他宝石即可使用的解决方案:

let(:rest_client_double) { instance_double(Some::REST::Client, create_thing: response) }

it 'sends get request to the RestClient' do
  allow(Some::REST::Client).to receive(:new).and_return(rest_client_double)

  MyModel.new(attrs).do_a_rest_call(some_str)

  expect(rest_client_duble).to have_received(:create_thing).with(some_str).once
end

基本上,您正在为REST客户端创建一个double。 然后,确保在调用Some::REST::Client.new时将使用双精度值(而不是真正的REST客户端实例)。

最后,您在模型上调用一个方法,并检查是否两次收到给定消息。