2011-12-20 33 views
14

我在我的Rails應用程序中使用SendGrid的SMTP API發送電子郵件。但是,我遇到了使用RSpec測試電子郵件頭(「X-SMTPAPI」)的麻煩。如何使用RSpec測試電子郵件標題

這裏的電子郵件是什麼樣子(從的ActionMailer :: Base.deliveries檢索):

#<Mail::Message:2189335760, Multipart: false, Headers: 
<Date: Tue, 20 Dec 2011 16:14:25 +0800>, 
<From: "Acme Inc" <[email protected]>>, 
<To: [email protected]>, 
<Message-ID: <[email protected]>>, 
<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":["[email protected]"]}>> 

這裏是我的規格代碼(失敗):

ActionMailer::Base.deliveries.last.to.should include("[email protected]") 

我也嘗試過各種方法來檢索標題(「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"] 

檢索電子郵件地址的陣列。

回答

9

的email_spec寶石有一堆的匹配,使這更容易,你可以做的東西一樣

mail.should have_header('X-SMTPAPI', some_value) 
mail.should deliver_to('[email protected]') 

而且細讀源創業板應該指向你在正確的方向,如果你不想要的使用它,例如

mail.to.addrs 

回報你的電子郵件地址(而不是這樣的東西「鮑勃」)

mail.header['foo'] 

讓你現場爲Foo頭(取決於你檢查什麼你可能想要撥打to_s就可以得到實際的字段值)

+0

謝謝。我已經檢出了email_spec寶石。 「deliver_to」匹配器類似於「to」匹配器(返回「[email protected]」而不是「[email protected]」),「have_header」匹配器只返回完整的頭部。無論如何,我已經找到了解決方案,現在將它發佈。謝謝! – 2011-12-20 10:37:06