You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在RSpec中如何验证FaxJob执行时会调用Fax类的new与send!方法

实现方案

首先需要先修正FaxJob的参数遗漏问题,原代码中perform方法没有接收number参数,调整如下:

class FaxJob
  # 补全参数接收,若为Rails Active Job需继承ApplicationJob
  def perform(number)
    Fax.new(number).send!
  end
end

以下是FaxJobSpec的RSpec测试实现:

# Rails项目引入rails_helper,纯Ruby项目引入rspec_helper
require 'rails_helper'

RSpec.describe FaxJob, type: :job do
  describe '#perform' do
    it '调用Fax.new传入正确参数并执行send!方法' do
      test_number = '13800138000'
      # 创建Fax实例测试替身,预设会收到send!调用
      fax_instance = instance_double(Fax)
      expect(fax_instance).to receive(:send!)
      
      # 预设Fax类会收到new调用,传入测试手机号后返回上面的测试替身
      expect(Fax).to receive(:new).with(test_number).and_return(fax_instance)
      
      # 执行任务
      FaxJob.perform_now(test_number)
    end
  end
end

如果想要更简洁的写法,可以用消息链匹配器,效果完全一致:

RSpec.describe FaxJob, type: :job do
  describe '#perform' do
    it '调用Fax.new(number).send!' do
      test_number = '13800138000'
      expect(Fax).to receive_message_chain(:new, :send!).with(test_number).with(no_args)
      FaxJob.perform_now(test_number)
    end
  end
end

如果你没有使用Rails Active Job,只是纯Ruby实现的任务类,把测试里的FaxJob.perform_now(test_number)换成FaxJob.new.perform(test_number)即可。

内容的提问来源于stack exchange,提问作者Piyush Chaudhary

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 23:36:00