Rspec 测试调用服务函数
Rspec test that service function is called
我有一个服务,我想测试是否调用了一个函数。我不确定如何测试它,因为它似乎没有正在执行的 subject
。
class HubspotFormSubmissionService
def initialize(form_data)
@form_data = form_data
end
def call
potential_client = createPotentialClient
end
def createPotentialClient
p "Step 1: Attempting to save potential client to database"
end
end
我想测试 createPotentialClient
被调用:
require 'rails_helper'
RSpec.describe HubspotFormSubmissionService, type: :model do
describe '#call' do
let(:form_data) { {
"first_name"=>"Jeremy",
"message"=>"wqffew",
"referrer"=>"Another Client"
} }
it 'attempts to process the form data' do
expect(HubspotFormSubmissionService).to receive(:createPotentialClient)
HubspotFormSubmissionService.new(form_data).call
end
end
end
我应该怎么做?
你可以这样设置主题。然后在测试中期望 subject 像你在模拟之后一样接收方法。我还会对 createPotentialClient
进行单独测试,以测试它是否返回了您期望的值。
subject { described_class.call }
before do
allow(described_class).to receive(:createPotentialClient)
end
it 'calls the method' do
expect(described_class).to receive(:createPotentialClient)
subject
end
我有一个服务,我想测试是否调用了一个函数。我不确定如何测试它,因为它似乎没有正在执行的 subject
。
class HubspotFormSubmissionService
def initialize(form_data)
@form_data = form_data
end
def call
potential_client = createPotentialClient
end
def createPotentialClient
p "Step 1: Attempting to save potential client to database"
end
end
我想测试 createPotentialClient
被调用:
require 'rails_helper'
RSpec.describe HubspotFormSubmissionService, type: :model do
describe '#call' do
let(:form_data) { {
"first_name"=>"Jeremy",
"message"=>"wqffew",
"referrer"=>"Another Client"
} }
it 'attempts to process the form data' do
expect(HubspotFormSubmissionService).to receive(:createPotentialClient)
HubspotFormSubmissionService.new(form_data).call
end
end
end
我应该怎么做?
你可以这样设置主题。然后在测试中期望 subject 像你在模拟之后一样接收方法。我还会对 createPotentialClient
进行单独测试,以测试它是否返回了您期望的值。
subject { described_class.call }
before do
allow(described_class).to receive(:createPotentialClient)
end
it 'calls the method' do
expect(described_class).to receive(:createPotentialClient)
subject
end