Ruby on rails 如何在RSPEC中存根邮件传递

Ruby on rails 如何在RSPEC中存根邮件传递,ruby-on-rails,rspec,actionmailer,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) 但上述功能显然失败,GenericMa

我想存根发送电子邮件,并返回样本电子邮件结果,以便进一步处理

鉴于我有:

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没有实现:deliver
或deliver!正如所尝试的那样

我想返回一些数据,因为我需要测试以下内容(以及更多内容):


GenericMailer.send\u通知
正在返回类的对象
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 info

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)

:deliver
更改为
:deliver?@CaTs我以前试过,但错误与上面相同。是否返回电子邮件内容?@Anthony yes:)
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)