使用 Rspec 进行测试时,将电子邮件存储在 ActionMailer::Base.deliveries 数组中

Store emails in ActionMailer::Base.deliveries array when testing with Rspec

我正在为 ruby on rails 4 应用程序中的未来功能编写测试。阅读 RoR 指南后,我发现我可以更改我的 config/environments/test.rb 文件中的 smtp 设置,以将电子邮件存储在一个数组中,而不是实际发送它们。进行更改后,当 运行 我的功能规格时,我的收件箱中仍会收到电子邮件。

environments/test.rb

# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test

在生产中,我的电子邮件是通过 Mandrill API 发送出去的。 为了仔细检查我的测试是 运行 在测试环境中,我 运行: "RAILS_ENV=test rspec spec" 并且它仍然发送了电子邮件。

功能规范

# Excerpt of feature spec
email = ActionMailer::Base.deliveries.last
email.body.raw_source.should include "Welcome!"

以上代码失败并显示以下消息:

expected to find text "Welcome!" in ""

如果我没记错的话,电子邮件似乎没有存储在 ActionMailer::Base.deliveries 数组中。

阅读了有关 mandrill_mailer gem 的更多信息后,我了解了如何处理离线测试。问题是因为我使用的是 mandrill 的 API,无法使用 ActionMailer 的标准 SMTP 拦截方法来拦截电子邮件。

在我添加的功能规范中:

email = MandrillMailer::deliveries.last
expect(email).to_not be_nil

我还添加了以下内容 spec_helper.rb

require 'mandrill_mailer/offline'