如何准确计算 Rails Cucumber 测试中发送的多封电子邮件

How to accurately count multiple emails being sent in Rails Cucumber Tests

我有一个 Cucumber 测试可以驱赶填写表格的人,其输出应该是两封电子邮件(一封给用户,一封给管理员)。

设置

this guide 之后,我已经围绕标记为 @email 的任何场景设置了包装器。

Around('@email') do |_scenario, block|
  ActionMailer::Base.delivery_method = :test
  ActionMailer::Base.perform_deliveries = true
  ActionMailer::Base.deliveries.clear
  block.call
end

ActionMailer::Base.delivery_method = :test 已在我的 config/environments/test.rb 文件中设置。

场景看起来像这样(经过编辑删除了商业用语)

@email
Scenario: Can find out more
  Given I am a visitor
  When I visit a page
  And I complete the form
  Then I should get an email, as should the admin

相关定义为;

When(/^I complete the form$/) do
  fill_in('Email Address', with: 'test@test.com')
  fill_in('Name', with: 'Test Name')
  click_button('Subscribe')
end

Then(/^I should get an email, as should the admin$/) do
  expect(ActionMailer::Base.deliveries.size).to eq 2
end

代码

此代码在本地执行干 运行 时有效,只是未在测试中。

def subscribe
  SubscribeMailer.user_subscribe(params[:email]).deliver_later

  SubscribeMailer.subscribe_email(params[:name],
                                  params[:email],
                                  request.referrer).deliver_later
  redirect_to subscribe_thanks_path
end

user_subscribesubscribe_email只是创建一些实例变量并调用mail

在周围放置一些调试器,我可以看到我希望受到攻击的系统的所有部分似乎都是如此。

预期结果

我希望它总是发送两封电子邮件(如果我做错了什么,则发送零封电子邮件)。

实际结果

我收到的始终是一封电子邮件。

我收到的电子邮件是 user_subscribe 一封。

我找到了解决方案。

我正在使用 Rails 5,在 4 和 5 之间,config.active_job.queue_adapter 的默认行为发生了变化。

config.active_job.queue_adapter = :inline 添加到 config/environments/test.rb 中解决了这个问题。它现在可以准确计算发送的电子邮件。