2011-02-23 30 views
5

我有一封邮件通过GMail帐户发送,我想测试一下ActionMailer实际上可以使用我提供的凭据登录到GMail的SMTP服务器。测试这个最好的方法是什么?你如何测试Rails邮件信息是否有效?

+0

你想要测试什么?你的凭证是正确的,还是ActionMailer实际上有效? – 2011-02-23 01:54:58

+0

凭据是正确的。我相信ActionMailer的作品。只是想让我的测试抓住它,如果我手动更改密码但忘记更新我的代码。 – XZVASFD 2011-02-23 23:36:52

回答

9

这不是一个完整的堆栈解决方案,但您可以直接使用Net :: SMTP检查服务器验证是否正确。 Rails所3个用来发送电子邮件的ActionMailer邮件宝石使用邮件像这样(与你的ActionMailer.smtp_settings):

#line 96 of mail-2.2.7/lib/mail/network/delivery_methods/smtp.rb 
    smtp = Net::SMTP.new(settings[:address], settings[:port]) 
    if settings[:enable_starttls_auto] 
    smtp.enable_starttls_auto if smtp.respond_to?(:enable_starttls_auto) 
    end 

    smtp.start(settings[:domain], settings[:user_name], settings[:password], 
    settings[:authentication]) do |smtp| 
    smtp.sendmail(message, envelope_from, destinations) 
    # @Mason: this line need not be included in your code. SMTP#start throws 
    # a Net::SMTPAuthenticationError if the authentication was not successful. 
    # So just putting this call to #start with an empty block in a method and 
    # calling assert_no_raise Net::SMTPAuthenticationError should do the trick. 
    # The empty block is necessary so that the connection gets closed. 
    # Reference #{rubydir}/lib/ruby/1.8/net/smtp.rb for more info. 
    end 

貌似的ActionMailer :: Base.smtp_settings是访问过:

settings = ActionMailer::Base.smtp_settings 

把在你的测试和评论上面提到的上面的行应该有一个工作的例子给你。

+0

真棒。谢谢蒂姆,并且很抱歉花了这么长时间来尝试并接受! – XZVASFD 2011-10-26 01:02:57

5
smtp = Net::SMTP.new settings[:address], settings[:port] 
smtp.enable_starttls_auto if settings[:enable_starttls_auto] 
smtp.start(settings[:domain]) do 
    expect { 
    smtp.authenticate settings[:user_name], settings[:password], settings[:authentication] 
    }.to_not raise_error 
end 

如果身份验证失败,调用authenticate将引发Net::SMTPAuthenticationError

否则,它将返回一个Net::SMTP::Response,并且调用status上的响应将返回"235"

+0

据我所知,在我自己的测试中,authenticate在认证失败时不会引发错误。如果提供了错误的密码,它将在'.string'中返回以下消息,例如:'535身份验证失败:错误的用户名/密码'。 – theGreenCabbage 2017-07-11 23:58:05