如何在 RSPEC 中存根 Mailer 交付

ald*_*n.h 4 rspec ruby-on-rails actionmailer

我想存根发送电子邮件并返回示例电子邮件结果以供进一步处理。

鉴于我有:

message = GenericMailer.send_notification(id).deliver!
Run Code Online (Sandbox Code Playgroud)

我想做类似的事情:

allow(GenericMailer).to receive_message_chain(:send_notification, :deliver)
   .and_return(mail_result_no_idea_what_is_like)
Run Code Online (Sandbox Code Playgroud)

但是上面的功能明显失效了,GenericMailer does not implement: deliver还是deliver!试过。

我想返回一些数据,因为我需要测试类似(和更多)的东西:

message.header.select{|h| h.name == "Date"}.try(:first).try(:value).try(:to_datetime).try(:utc)
Run Code Online (Sandbox Code Playgroud)

小智 6

GenericMailer.send_notification 正在返回一个类的对象 ActionMailer::MessageDelivery

rails 5.1.4rspec 的示例3.6.0

it 'delivers notification' do
  copy = double()
  expect(GenericMailer).to receive(:send_notification).and_return(copy)
  expect(copy).to receive(:deliver!) # You can use allow instead of expect
  GenericMailer.send_notification.deliver!
end
Run Code Online (Sandbox Code Playgroud)