ruby-on-rails Rspec是否忽略允许块?

anauzrmj  于 2022-11-19  发布在  Ruby
关注(0)|答案(1)|浏览(259)

我想测试一个调用hubspot API(GET /crm/v3/owners/{ownerId})端点的Rails作业,并使用请求结果的信息更新记录。
问题是我使用this gem作为API Package 器,我的before块似乎被忽略了,因为结果显示API调用不能用这个owner_id给予我一个所有者对象(作为attributes参数给出的那个显然是假的)。一个before块应该覆盖控制器的“正常”响应,不是吗?
我真的不知道我做错了什么。
更多背景信息:

我的工作代码

module Hubspots
  module Contracts
    class UpdateJob < BaseJob
      queue_as :high_priority

      def perform(attributes)
        contract = Contract.find_by(hubspot_sales_deal_id: attributes[:hubspot_sales_deal_id])
        return if contract.nil?

        deal_owner = client.crm.owners.owners_api.get_by_id(owner_id: attributes[:hubspot_tailor_deal_owner],
                                                            id_property: 'id', archived: false)

        attributes[:hubspot_tailor_deal_owner] = get_owner_name(deal_owner)

        contract.update!(attributes)
      end

      private

      def get_owner_name(hubspot_owner_object)
        "#{hubspot_owner_object.last_name.upcase} #{hubspot_owner_object.first_name.capitalize}"
      end
    end
  end
end

我的测试代码

RSpec.describe Hubspots::Contracts::UpdateJob, type: :job do
  let!(:job) { described_class.new }
  let(:perform) { job.perform(attributes) }
  let!(:contract) { create(:contract, hubspot_sales_deal_id: 123) }
  let!(:attributes) do
    { hubspot_tailor_deal_id: 456, hubspot_tailor_deal_owner: 876, hubspot_sales_deal_id: 123 }
  end
  let!(:deal_owner_api) { Hubspot::Client.new(access_token: ENV['HUBSPOT_ACCESS_TOKEN']).crm.owners.owners_api }
  let!(:deal_owner_properties) { { last_name: 'Doe', first_name: 'John' } }

  before do
    allow(deal_owner_api).to receive(:get_by_id).and_return(deal_owner_properties)
  end

  describe '#perform' do
    it 'updates contract' do
      expect { perform }.to change { contract.reload.hubspot_tailor_deal_owner }.from(nil)
                                                                                .to('DOE John')
    end
  end
end

测试结果x1c 0d1x

我尝试在谷歌上rtfm,但我还没有找到解决方案(我总是坏rtfm顺便说一句)

y1aodyip

y1aodyip1#

我的CTO最终通过使用the Webmock gem为我提供了解决方案
代码片段:

before do
    stub_request(:get, 'https://api.hubapi.com/crm/v3/owners/876?archived=false&idProperty=id')
      .with(headers: { 'Authorization' => "Bearer #{ENV['HUBSPOT_ACCESS_TOKEN']}" }).to_return(status: 200, body: {
        firstName: 'John',
        lastName: 'Doe'
      }.to_json, headers: {})
  end

  describe '#perform' do
    it 'updates contract' do
      expect { perform }.to change { contract.reload.hubspot_tailor_deal_owner }.from(nil)
                                                                                .to('DOE John')
    end
  end

相关问题