19

我在 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"] 

检索电子邮件地址数组。

4

2 回答 2

12

email_spec gem 有一堆匹配器可以让这更容易,你可以做类似的事情

mail.should have_header('X-SMTPAPI', some_value)
mail.should deliver_to('foo@bar.com')

如果您不想使用它,那么仔细阅读该宝石的来源应该会为您指明正确的方向,例如

mail.to.addrs

返回您的电子邮件地址(而不是像“鲍勃”这样的东西)

mail.header['foo']

为您获取 foo 标头的字段(取决于您正在检查的内容,您可能希望调用to_s它以获取实际的字段值)

于 2011-12-20T10:14:56.180 回答
0

在这里用更现代的 rspec 语法重复一些其他建议:

RSpec.describe ImportFile::Mailer do
  describe '.file_error' do
    let(:mail) { described_class.file_error('daily.csv', 'missing header') }

    it { expect(mail.subject).to eq("Import error: missing header in daily.csv") }
    it { expect(mail.header['X-source-file'].to_s).to eq ('daily.csv') }
  end
end
于 2020-10-08T13:45:48.730 回答