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

XZV*_*SFD 7 testing rspec ruby-on-rails actionmailer

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

Tim*_*ite 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
Run Code Online (Sandbox Code Playgroud)

看起来ActionMailer :: Base.smtp_settings也可以访问:

  settings = ActionMailer::Base.smtp_settings
Run Code Online (Sandbox Code Playgroud)

把它放在你的测试中并评论出上面提到的那条线应该有一个适合你的例子.


Jel*_*Cat 6

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
Run Code Online (Sandbox Code Playgroud)

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

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