0
votes

I'm trying to write an rspec test that will send an email using my custom delivery method for ActionMailer.

My custom delivery method implementation:

class MyCustomDeliveryMethod  

  def deliver!(message)
    puts 'Custom deliver for message: ' + message.to_s
    ...
  end

Rspec code:

it "should send an email" do
  WebMock.allow_net_connect!
  ActionMailer::Base.add_delivery_method( :api, MyCustomDeliveryMethod)
  ActionMailer::Base.perform_deliveries = true

  puts 'expecting this to call my custom delivery method'

  ActionMailer::Base.mail( :to => '[email protected]',
    :subject => 'here is a test subject sent by ActionMailer',
    :body => 'here is a test body sent by <i>ActionMailer</i>',
    :delivery_method => :api 
  )

end

test.rb

config.action_mailer.delivery_method = :api

However I never see the 'custom deliver' string. My other tests exercise the other methods of the class fine, it's just the triggering of the deliver!() method doesnt work. What am I missing?

(NB. there are a few examples around of testing ActionMailers with rspec, however they seem to refer to mocking the mailer behaviour, which is not what I want - I want the actual email to go out).

2
your MyCustomMailer mailer should be inherited from standart ActionMailer::Base, shouldn't it?Aleksey

2 Answers

2
votes

Got there in the end. There were two things missing:

The custom delivery class must define an initialise method that takes one parameter. e.g.

def initialize(it)
end

You need to .deliver_now the mail to get it to trigger, so the full calling code is e.g.

it "should send an email" do
  WebMock.allow_net_connect!
  ActionMailer::Base.add_delivery_method( :api, MyCustomDeliveryMethod)
  ActionMailer::Base.perform_deliveries = true

  puts 'expecting this to call my custom delivery method'

  ActionMailer::Base.mail( :to => '[email protected]',
    :subject => 'here is a test subject sent by ActionMailer',
    :body => 'here is a test body sent by <i>ActionMailer</i>',
    :delivery_method => :api 
  ).deliver_now

end
0
votes

I am not quite sure but I think the problem is that your MyCustomMailer class is not inherited from ActionMailer::Base.

Check this docs.
Here ApplicationMailer is inherited from ActionMailer::Base and used to set some default values.

And actual mailer class UserMailer is inherited from ApplicationMailer.
If you like you can skip extra class and inherit directly, i.e

class MyCustomMailer < ActionMailer::Base
  ...
end