How to write an RSpec for a Mail Interceptor?
Asked Answered
C

1

17

I'm using a mail interceptor as follows:

setup_mail.rb

Mail.register_interceptor(MailInterceptor) if Rails.env != "production" 

class MailInterceptor

class MailInterceptor  
  def self.delivering_email(message)  
    message.subject = "#{message.subject} [#{message.to}]"
    message.to = "[email protected]"
  end
end

I'm unable to create an rspec for this interceptor as it is not happen with rake spec.

I have the following spec:

  describe "MailInterceptor" do 
    it "should be intercepted" do
      @email = UserMailer.registration_automatically_generated(@user)
      @email.should deliver_to("[email protected]")      
    end
  end

In the test.log I see that the deliver_to is not the interceptor. Any ideas on how I can write an rspec for the interceptor?

Thanks

Classic answered 3/10, 2011 at 19:0 Comment(2)
does the interceptor work in dev? where is setup_mail.rb stored?Tingaling
Yes it is setup in initalizers/setup_mail.rb w Mail.register_interceptor(MailInterceptor) if Rails.env != "production"Classic
T
15

The email_spec matcher for deliver_to doesn't actually run the mail message through the typical delivery methods, it simply inspects the message for who it is being sent to.

To test your interceptor, you can invoke the delivering_email method directly

it 'should change email address wen interceptor is run' do
  email = UserMailer.registration_automatically_generated(@user)
  MailInterceptor.delivering_email(email)
  email.should deliver_to('[email protected]')
end

The other option is to let the message deliver as normal, and test that it was sent to the right place using email_spec's last_email_sent

it 'should intercept delivery' do
  reset_mailer
  UserMailer.registration_automatically_generated(@user).deliver
  last_email_sent.should deliver_to('[email protected]')
end

It might be a good idea to use both tests, the first to make sure that MailInterceptor is altering the message as you would expect. The second test is more of an integration test, testing that MailInterceptor is hooked in to the delivery system.

Tingaling answered 8/10, 2011 at 0:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.