How to stub Mailer delivery in RSPEC

Viewed 3399

I want to stub sending email and return sample email result for further process.

Given I have:

message = GenericMailer.send_notification(id).deliver!

I want to do something like:

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

but above function obviously fails, GenericMailer does not implement: deliver or deliver! as tried.

I want to return some data as i need to test something like (and more):

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

GenericMailer.send_notification is returning an object of class ActionMailer::MessageDelivery

Example with rails 5.1.4 and 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

Finally came up with a solution. Thanks to @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)
Related