我有一个:after_update
钩子,可以在订单状态更改时发送电子邮件。由于:order_status_id_chaned?
返回false,因此似乎无法通过以下测试。
测试:
context 'when the order_status changes' do
it 'should send an email' do
@order2.save
expect(subject).to receive(:send_confirmation_email)
@order2.update(order_status_id: 2)
end
end
Order.rb
class Order < ApplicationRecord
after_update :send_confirmation_email, if: :order_just_submitted?
def order_just_submitted?
p self.order_status_id_changed? # prints false
p self.is_submitted? # prints true
self.order_status_id_changed? and self.is_submitted?
end
def send_confirmation_email
...
end
end
您知道为什么:order_status_id_chaned?
在更新值后返回false吗?
答案 0 :(得分:1)
order_status_id_changed?
在被调用时为假,因为它仅在更新后被调用。保存记录后,更改将移至previous_changes
中,因此您可以执行以下操作:
def order_just_submitted?
previous_changes.keys.include?('order_status_id') && is_submitted?
end
此外,除非您希望在任何状态更改时触发电子邮件,否则您可能要检查状态更改为什么。