簡體   English   中英

如何在RSPEC中存根Mailer傳遞

[英]How to stub Mailer delivery in RSPEC

我想存根發送電子郵件並返回示例電子郵件結果以進行進一步處理。

鑒於我有:

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)

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

最后想出了一個解決方案。 感謝@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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM