如何查看邮件是否在 rspec 中发送

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 验证邮件已发送的测试用例

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

错误

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

在邮件规范中

如果是邮件规范,您可以检查邮件的发件人、收件人和主题,如下所示。

   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

在控制器规范中,当电子邮件设置为 deliver_now

您也可以在控制器规范中验证电子邮件是否已发送。

  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

在控制器规范中,当电子邮件设置为 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