have_enqueued_mail 匹配器

have_enqueued_mail(也称为 enqueue_mail)匹配器用于检查是否排队了给定的邮件程序。

背景

假设 存在活动作业。

检查邮件程序类和方法名称

假设 存在名为“spec/mailers/usermailerspec.rb”的文件,其中包含

require "rails_helper"

RSpec.describe NotificationsMailer do
  it "matches with enqueued mailer" do
    ActiveJob::Base.queue_adapter = :test
    expect {
      NotificationsMailer.signup.deliver_later
    }.to have_enqueued_mail(NotificationsMailer, :signup)
  end
end

我运行 rspec spec/mailers/user_mailer_spec.rb

然后示例应该全部通过。

检查邮件程序排队时间

假设 存在名为“spec/mailers/usermailerspec.rb”的文件,其中包含

require "rails_helper"

RSpec.describe NotificationsMailer do
  it "matches with enqueued mailer" do
    ActiveJob::Base.queue_adapter = :test
    expect {
      NotificationsMailer.signup.deliver_later(wait_until: Date.tomorrow.noon)
    }.to have_enqueued_mail.at(Date.tomorrow.noon)
  end
end

我运行 rspec spec/mailers/user_mailer_spec.rb

然后示例应该全部通过。

检查邮件程序参数

假设 存在名为“app/mailers/my_mailer.rb”的文件,其中包含

class MyMailer < ApplicationMailer

  def signup(user = nil)
    @user = user

    mail to: "to@example.org"
  end
end

假设 存在名为“spec/mailers/mymailerspec.rb”的文件,其中包含

require "rails_helper"

RSpec.describe MyMailer do
  it "matches with enqueued mailer" do
    ActiveJob::Base.queue_adapter = :test
    # Works with plain args
    expect {
      MyMailer.signup('user').deliver_later
    }.to have_enqueued_mail(MyMailer, :signup).with('user')
  end
end

我运行 rspec spec/mailers/my_mailer_spec.rb

然后示例应该全部通过。

参数化邮件程序

假设 存在名为“app/mailers/my_mailer.rb”的文件,其中包含

class MyMailer < ApplicationMailer

  def signup
    @foo = params[:foo]

    mail to: "to@example.org"
  end
end

假设 存在名为“spec/mailers/mymailerspec.rb”的文件,其中包含

require "rails_helper"

RSpec.describe MyMailer do
  it "matches with enqueued mailer" do
    ActiveJob::Base.queue_adapter = :test
    # Works with named parameters
    expect {
      MyMailer.with(foo: 'bar').signup.deliver_later
    }.to have_enqueued_mail(MyMailer, :signup).with(a_hash_including(params: {foo: 'bar'}))
  end
end

我运行 rspec spec/mailers/my_mailer_spec.rb

然后示例应该全部通过。

参数化并向邮件程序传递参数

假设 存在名为“app/mailers/my_mailer.rb”的文件,其中包含

class MyMailer < ApplicationMailer

  def signup(user)
    @user = user
    @foo = params[:foo]

    mail to: "to@example.org"
  end
end

假设 存在名为“spec/mailers/mymailerspec.rb”的文件,其中包含

require "rails_helper"

RSpec.describe MyMailer do
  it "matches with enqueued mailer" do
    ActiveJob::Base.queue_adapter = :test
    # Works also with both, named parameters match first argument
    expect {
      MyMailer.with(foo: 'bar').signup('user').deliver_later
    }.to have_enqueued_mail(MyMailer, :signup).with(params: {foo: 'bar'}, args: ['user'])
  end
end

我运行 rspec spec/mailers/my_mailer_spec.rb

然后示例应该全部通过。