Search code examples
ruby-on-railsruby-on-rails-4rspecactionmailerrspec-rails

How to check mail is sent in rspec


Actionmailer

def welcome_send(user)
        @user = user
        mail to: user.email, subject: 'Welcome to my site', from: 'suhasmv29@gmail.com'
    end

RSpec test case to verify mail has been sent

it "sends a confirmation email" do
      expect { mail.to }.to change { ActionMailer::Base.deliveries.count }.by(1)
    end

Error

expected `ActionMailer::Base.deliveries.count` to have changed by 1, but was changed by 0


Solution

  • In mailer spec

    If it the mailer spec, you can check the from, to and the subject of the email like below.

       it 'sends a confirmation email' do
         expect do
           perform_enqueued_jobs do # To perform the job 
             UserMailer.welcome_send(user).deliver_later # Create and send user         
           end
         end.to change { ActionMailer::Base.deliveries.size }.by(1)
       end
    

    In controller spec & when the email is set to deliver_now

    You can also verify whether the email is sent in the controller spec too.

      it 'sends a confirmation email when a new user created' do
        expect do
          post :create, params: {}
        end.to change { ActionMailer::Base.deliveries.size }.by(1)
      end
    

    In controller spec & when the email is set to deliver_later

    it 'should enqueue a mailer job' do
       expect do
         post :create, params: {}
       end.to have_enqueued_job.exactly(:once).and have_enqueued_job(ActionMailer::DeliveryJob)
    end