我在 Rails 应用程序中使用 SendGrid 的SMTP API来发送电子邮件。但是,我在使用 RSpec 测试电子邮件标头(“X-SMTPAPI”)时遇到了麻烦。
这是电子邮件的样子(从 ActionMailer::Base.deliveries 检索):
#<Mail::Message:2189335760, Multipart: false, Headers:
<Date: Tue, 20 Dec 2011 16:14:25 +0800>,
<From: "Acme Inc" <contact@acmeinc.com>>,
<To: doesntmatter@nowhere.com>,
<Message-ID: <4ef043e1b9490_4e4800eb1b095f1@Macbook.local.mail>>,
<Subject: Your Acme order>, <Mime-Version: 1.0>,
<Content-Type: text/plain>, <Content-Transfer-Encoding: 7bit>,
<X-SMTPAPI: {"sub":{"|last_name|":[Foo],"|first_name|":[Bar]},"to":["foo@bar.com"]}>>
这是我的规范代码(失败):
ActionMailer::Base.deliveries.last.to.should include("foo@bar.com")
我还尝试了各种方法来检索标头(“X-SMTPAPI”),但也没有用:
mail = ActionMailer::Base.deliveries.last
mail.headers("X-SMTPAPI") #NoMethodError: undefined method `each_pair' for "X-SMTPAPI":String
帮助?
更新(答案)
事实证明,我可以这样做来检索电子邮件标头的值:
mail.header['X-SMTPAPI'].value
但是,返回值是 JSON 格式。然后,我需要做的就是解码它:
sendgrid_header = ActiveSupport::JSON.decode(mail.header['X-SMTPAPI'].value)
它返回一个哈希,我可以在其中执行此操作:
sendgrid_header["to"]
检索电子邮件地址数组。