【问题标题】:how do you test that Rails mailer credentials are valid?您如何测试 Rails 邮件程序凭据是否有效?
【发布时间】:2011-07-02 10:34:35
【问题描述】:

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

【问题讨论】:

  • 你想测试什么?您的凭据是否正确,或者 ActionMailer 确实有效?
  • 凭据正确。我相信 ActionMailer 有效。如果我手动更改密码但忘记更新我的代码,只是希望我的测试能够捕捉到它。

标签: ruby-on-rails testing rspec actionmailer


【解决方案1】:

这不是一个全栈解决方案,但您可以通过直接使用 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

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

【讨论】:

  • 太棒了。谢谢蒂姆,很抱歉花了这么长时间尝试并接受!
【解决方案2】:
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"

【讨论】:

  • 据我自己的测试所知,authenticate 在身份验证失败时不会引发错误。如果提供了错误的密码,它将在.string 中返回以下消息,例如:535 Authentication failed: Bad username / password
猜你喜欢
  • 2014-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-25
相关资源
最近更新 更多