我有一个带有简单:after_update
回调的模型,由于某种原因该回调没有触发。我进行了一项测试,检查该函数是否已调用并通过,但是由于某种原因,实际上没有任何反应。
class HealthProfile < ApplicationRecord
after_update :send_office_email
def send_office_email
p "sending office email"
email = MailjetService.new(ID)
Rails.application.routes.default_url_options[:host] = 'host_name'
message = email.send_email('email', self.location.email, "New Health Profile: #{self.name}", {
"office_name" => self.location.name,
"name" => self.name,
"url" => Rails.application.routes.url_helpers.health_profile_url(self)
})
p message
end
end
测试:
require 'rails_helper'
RSpec.describe HealthProfile, type: :model do
before(:each) do
@hp = build(:health_profile)
end
it 'emails office on update (complete - w/ signature)' do
p 1
@hp.save
p 2
expect(@hp).to receive(:send_office_email)
p "updating signature to true..."
@hp.update(signature: 't')
p 3
end
end
在测试输出中,我看到以下内容:
1
2
"updating signature to true..."
3
但是我从没见过sending office email
。测试通过,表明该模型已收到回调,但该回调中没有任何内容运行。我想念什么?
答案 0 :(得分:1)
实际上,我相信您的测试正在正常进行。如果不是,则您的测试会因expected to receive "send_office_email" but nothing was called
而失败。
expect to_receive
在对象上添加了方法,导致生成的伪方法不会调用您的原始方法。
尝试一下。
require 'rails_helper'
RSpec.describe HealthProfile, type: :model do
let(:hp) { build(:health_profile) }
it 'emails office on update (complete - w/ signature)' do
p 1
hp.save
p 2
p "updating signature to true..."
hp.update(signature: 't')
p 3
end
end