在Ruby on Rails的,我在我想我的应用程序(在特定的测试环境)的情况下拦截应用程序生成的所有外发邮件,而是将它们发送到不同的测试地址(也许还修改体说“最初发送到:...”)。
我看到的ActionMailer有一些钩子观察或拦截邮件,但我不希望分拆自己的解决方案,如果有这样做的更简单的方法。建议?
我们正在使用中有很多成功的sanitize_email宝石。它发送的所有电子邮件到您指定的地址,并预置与原始收件人的主题。这听起来像它不正是你想要什么,并取得了QA-ING电子邮件微风我们。
通常,您在测试中做的是检查的ActionMailer :: Base.deliveries,这是TMail对象为已通过应用程序发送的邮件的数组。在测试环境中的默认设置是没有被交付,刚投入数组。
我也想看看在测试中使用email_spec。远远超过滚动自己的测试功能方便。使用email_spec,水豚的辅助功能和网络的步骤,和factory_girl之间,这是接近的测试应用程序的表面面积的80%,在大多数我的应用程序。
老问题,但在谷歌第一击...
我最终使用delivery_method = :sendmail
解决了这个由(AB)以不同的方式,这有效刚刚管道邮件到可执行的东西;这被认为是sendmail
,但它可以是任何东西,真的。
在你config/environments/development.rb
,你可以这样做:
YourApp::Application.configure do
# [...]
config.action_mailer.delivery_method = :sendmail
config.action_mailer.sendmail_settings = {
location: "#{Rails.root}/script/fake-sendmail",
arguments: '[email protected]',
}
end
然后进行script/fake-sendmail
:
#!/bin/sh
sendmail -if [email protected] "$1" < /dev/stdin
(不要忘记,使这个可执行文件!)
一个相关的解决方案(我喜欢)是只将其追加到MBOX文件;这需要很少的设置。
该config/environments/development.rb
类似于:
YourApp::Application.configure do
# [...]
config.action_mailer.delivery_method = :sendmail
config.action_mailer.sendmail_settings = {
location: "#{Rails.root}/script/fake-sendmail",
arguments: "'#{Rails.root}/tmp/mail.mbox'",
}
end
而script/fake-sendmail
现在看起来像:
#!/bin/sh
echo "From FAKE-SENDMAIL $(date)" >> "$1"
cat /dev/stdin >> "$1"
echo >> "$1"
打开与$any
电子邮件客户端的MBOX文件...
这是一个非常简单的方法,这似乎工作得很好。更多的细节can be found here(我是这个页面的作者)。
这是现在非常简单,Action Mailer interceptors做。
拦截器可以很容易地改变接收地址,主题和发送邮件的其他细节。只需定义拦截器,然后在init
文件注册。
LIB / sandbox_mail_interceptor.rb
# Catches outgoing mail and redirects it to a safe email address.
module SandboxMailInterceptor
def self.delivering_email( message )
message.subject = "Initially sent to #{message.to}: #{message.subject}"
message.to = [ ENV[ 'SANDBOX_EMAIL' ] ]
end
end
配置/ INIT / mailers.rb
require Rails.root.join( 'lib', 'sandbox_mail_interceptor' )
if [ 'development', 'staging' ].include?( Rails.env )
ActionMailer::Base.register_interceptor( SandboxMailInterceptor )
end
您也可以随时注销拦截如果,例如,你需要测试的原始电子邮件,而不拦截器的干扰。
Mail.unregister_interceptor( SandboxMailInterceptor )
# Test the original, unmodified email.
ActionMailer::Base.register_interceptor( SandboxMailInterceptor )