我有一份作業,我目前正在使用 RSpec 進行測驗:
# app/jobs/do_something_job.rb
class DoSomethingJob < ApplicationJob
def perform(a, b, c)
Service.new(a, b, c).call
end
end
示例檔案如下所示:
require 'spec_helper'
describe DoSomethingJob do
it do
expect { described_class.perform_later(a, b, c) }.to have_enqueued_job
end
end
這個例子肯定成功了,無論perform方法體中發生什么,它都會將作業排入佇列。
現在,如果我更新Service該類,例如洗掉其initialize方法上的引數,則以這種方式離開:
class Service
def initialize(a, b)
...
end
end
而且我不更新作業示例,它無論如何都會成功,因為作業已入隊。我想要做的是測驗DoSomethingJob#perform執行的主體沒有錯誤,而不是了解其Service本身的細節(它有自己的測驗)。
我嘗試模擬 Service 并使用expect { ... }.not_to raise_error,但這會偽造測驗,因為我必須存根它收到的new和call方法。
有沒有辦法實作這一目標?
uj5u.com熱心網友回復:
首先在服務上創建一個類方法,這樣你就不必存根實體:
class Service
def self.call(a, b, c)
new(a, b, c).call
end
end
# app/jobs/do_something_job.rb
class DoSomethingJob < ApplicationJob
def perform(a, b, c)
Service.call(a, b, c)
end
end
然后只需對您希望該方法執行的操作(在這種情況下呼叫合作者)提出期望并立即執行作業:
describe DoSomethingJob do
it "calls Service with a, b, c" do
expect(Service).to receive(:call).with(1, 2, 3).and_call_original
DoSomethingJob.perform_now(1, 2, 3)
end
end
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/314934.html
上一篇:獲取具有Rails關系的專案
