Clearing out ActionMailer::Base.deliveries after RSpec test Clearing out ActionMailer::Base.deliveries after RSpec test ruby-on-rails ruby-on-rails

Clearing out ActionMailer::Base.deliveries after RSpec test


RSpec.describe UserMailer do  before do    # ActionMailer::Base.deliveries is a regular array    ActionMailer::Base.deliveries = []    # or use ActionMailer::Base.deliveries.clear  end  it "sends welcome email" do    user = create(:user)    UserMailer.welcome_email(user).deliver_now    expect(ActionMailer::Base.deliveries).to be_present  endend


You can clear the deliveries after each test quite easily, adding this into your spec_helper.rb.

RSpec.configure do |config|  config.before { ActionMailer::Base.deliveries.clear }      end

I'd suggest reading my article about the correct emails configuration in Rails where I talk also about testing them correctly.


As Andy Lindeman points out, clearing the deliveries is done automatically for mailer tests. However, for other types, simply add , :type => :mailer to the wrapping block to force the same behavior.

describe "tests that send emails", type: :mailer do  # some testsend