【问题标题】:How to test email headers using RSpec如何使用 RSpec 测试电子邮件标头
【发布时间】:2012-01-24 05:55:00
【问题描述】:

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

检索电子邮件地址数组。

【问题讨论】:

    标签: ruby-on-rails rspec ruby-on-rails-3.1 rspec-rails sendgrid


    【解决方案1】:

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

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

    如果您不想使用它,仔细阅读该 gem 的源代码应该可以为您指明正确的方向,例如

    mail.to.addrs
    

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

    mail.header['foo']
    

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

    【讨论】:

    • 谢谢。我已经检查了 email_spec gem。 “deliver_to”匹配器类似于“to”匹配器(返回“doesntmatter@nowhere.com”而不是“foo@bar.com”),“have_header”匹配器只返回完整的标题。无论如何,我已经找到了解决方案,现在将其发布。谢谢!
    【解决方案2】:

    在这里用更现代的 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-20
      • 1970-01-01
      • 1970-01-01
      • 2015-07-26
      相关资源
      最近更新 更多