开发者

Clearing out ActionMailer::Base.deliveries after RSpec test

I have the following RSpec test for my UserMailer class:

require "spec_helper"

describe UserMailer do
  it "should send welcome emails" do
    ActionMailer::Base.deliveries.should be_empty
    user = Factory(:user)
    UserMailer.welcome_email(user).deliver
    ActionMailer::Base.deliveries.should_not be_empty
  end
end

This test passed the first time, but failed the second time I ran it. After doing a little 开发者_高级运维bit of debugging, it appears that the 1st test added an item to the ActionMailer::Base.deliveries array and that item never got cleared out. That causes the first line in the test to fail since the array is not empty.

What's the best way to clear out the ActionMailer::Base.deliveries array after an 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
  end
end


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 tests
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜