Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write an RSpec for a Mail Interceptor?

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

like image 960
AnApprentice Avatar asked Oct 03 '11 19:10

AnApprentice


1 Answers

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.

like image 87
danivovich Avatar answered Sep 28 '22 08:09

danivovich