你如何测试Rails邮件程序凭证是否有效?

时间:2011-02-23 01:09:36

标签: ruby-on-rails testing rspec actionmailer

我有一个邮件程序通过GMail帐户发送,我想测试ActionMailer是否可以使用我提供的凭据实际登录到GMail的SMTP服务器。测试这个的最佳方法是什么?

2 个答案:

答案 0 :(得分:10)

这不是一个完整的堆栈解决方案,但您可以直接使用Net :: SMTP检查服务器身份验证是否正确。 Rails 3用于发送ActionMailer电子邮件的Mail gem使用Mail(使用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

将它放在你的测试中并注释掉上面提到的那一行应该有一个适合你的例子。

答案 1 :(得分: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"