【问题标题】:Test the number of emails enqueued?测试排队的电子邮件数量?
【发布时间】:2021-08-17 18:27:28
【问题描述】:

我们可以检查enqueued_jobs.length,前提是电子邮件是唯一可能的后台作业类型。

it 'sends exactly one, particular email' do
  expect { post :create }.to(
    # First, we can check about the particular email we care about.
    have_enqueued_mail(MyMailer, :my_particular_email)
  )

  # But we also have to check that no other email was sent.
  expect(ActiveJob::Base.queue_adapter.enqueued_jobs.length).to eq(1)
end

有没有更好的方法来断言:

  1. MyMailer.my_particular_email 已入队,
  2. 没有其他电子邮件入队,
  3. 我们不在乎是否有其他非电子邮件后台作业入队

【问题讨论】:

    标签: ruby-on-rails ruby rspec rspec-rails rails-activejob


    【解决方案1】:
    # first filter MyMailer job 
    my_mail_jobs = ActiveJob::Base.queue_adapter.enqueued_jobs.select { |job|
      job[:job] == SendEmailsJob &&
      job[:args][0] == "MyMailer"
    }
    # check only once
    expect(my_mail_jobs.length).to eq(1) 
    # and that send to your particular email not other email
    expect(my_mail_jobs.first[:args]).to include("your particular email") 
    

    【讨论】:

    • 谢谢!我一直在尝试一些非常相似的东西,像你一样直接检查enqueued_jobs。这很尴尬,但这是我迄今为止找到的唯一解决方案。
    【解决方案2】:

    我相信once 将与此匹配器一起使用。

    expect {
      post :create
    }.to have_enqueued_mail(MyMailer, :my_particular_email).once
    

    【讨论】:

    • 谢谢!我认为once 可以工作是对的,但我还想断言没有其他邮件被排队。
    • @JaredBeck 我在 RSpec 中看不到任何内容。 assert_enqueued_emails(1) { post :create } 只是一个用于查找排队邮寄作业的包装器。见github.com/rails/rails/blob/master/actionmailer/lib/…
    • @JaredBeck 证明某些事情没有发生总是很棘手,而且在断言不应该发生的事情时,您总是必须划清界限,话虽如此,我不明白为什么 .not_to have_enqueued_mail(MyMailer, :this_should_not_have_beeen_sent) 不会工作...
    猜你喜欢
    • 2018-10-27
    • 2023-03-03
    • 1970-01-01
    • 2018-08-22
    • 1970-01-01
    • 2019-03-09
    • 2019-04-21
    • 2011-05-26
    • 1970-01-01
    相关资源
    最近更新 更多