send_email 匹配器

send_email 匹配器用于检查在期望块内是否发送了具有给定参数的电子邮件。

注意:此匹配器意味着示例实际上使用测试适配器发送电子邮件,而不是安排为稍后在后台发送的作业。

要使电子邮件在测试中发送,请确保:- ActionMailer 执行传递- Rails.application.config.action_mailer.perform_deliveries = true- 如果电子邮件异步发送(使用 .deliver_later 调用),ActiveJob 使用内联适配器- Rails.application.config.active_job.queue_adapter = :inline- ActionMailer 使用测试适配器- Rails.application.config.action_mailer.delivery_method = :test

如果您想检查电子邮件是否已安排为作业,请使用 have_enqueued_email 匹配器。

检查使用给定的多个参数发送的电子邮件

假设一个名为“spec/mailers/notificationsmailerspec.rb”的文件,其中包含

require "rails_helper"

RSpec.describe NotificationsMailer do
  it "checks email sending by multiple params" do
    expect {
      NotificationsMailer.signup.deliver_now
    }.to send_email(
      from: 'from@example.com',
      to: 'to@example.org',
      subject: 'Signup'
    )
  end
end

我运行 rspec spec/mailers/notifications_mailer_spec.rb

这些示例应该全部通过。

检查使用匹配参数发送的电子邮件

假设一个名为“spec/mailers/notificationsmailerspec.rb”的文件,其中包含

require "rails_helper"

RSpec.describe NotificationsMailer do
  it "checks email sending by one param only" do
    expect {
      NotificationsMailer.signup.deliver_now
    }.to send_email(
      to: 'to@example.org'
    )
  end
end

我运行 rspec spec/mailers/notifications_mailer_spec.rb

这些示例应该全部通过。

检查未使用给定参数发送的电子邮件

假设一个名为“spec/mailers/notificationsmailerspec.rb”的文件,其中包含

require "rails_helper"

RSpec.describe NotificationsMailer do
  it "checks email not sent" do
    expect {
      NotificationsMailer.signup.deliver_now
    }.to_not send_email(
      to: 'no@example.org'
    )
  end
end

我运行 rspec spec/mailers/notifications_mailer_spec.rb

这些示例应该全部通过。