如何在RSPEC中存根Mailer传递

时间:2018-10-26 05:28:33

标签: ruby-on-rails rspec actionmailer

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

鉴于我有:

message = GenericMailer.send_notification(id).deliver!

我想做类似的事情:

allow(GenericMailer).to receive_message_chain(:send_notification, :deliver)
   .and_return(mail_result_no_idea_what_is_like)

但以上功能显然失败了,GenericMailer does not implement: deliver或交付!如尝试的那样。

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

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

2 个答案:

答案 0 :(得分:2)

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

带有rails 5.1.4和rspec 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

答案 1 :(得分:0)

最后想出了一个解决方案。感谢@LolWalid信息。

copy = double()
# recursive_ostruct_even_array is my method to convert hash/array to OpenStruct Obje
message = recursive_ostruct_even_array({
                                         "header" => [{"name" => "Date", "value" => Time.now.utc}],
                                         "to" => ["test@gmail.com"],
                                         "from" => ["from@gmail.com"],
                                         "subject" => "For Testing",
                                         "body" => "-"
                                       })
allow(GenericMailer).to receive(:send_notification).and_return(copy)
allow(copy).to receive(:deliver!).and_return(message)