【问题标题】:RSpec sends emails (not storing in ActionMailer::Base.deliveries) - dont know why?RSpec 发送电子邮件(不存储在 ActionMailer::Base.deliveries 中) - 不知道为什么?
【发布时间】:2011-04-29 02:26:17
【问题描述】:

我正在使用 rspec,当我运行 rake spec 时,用户邮件程序通过 smtp 发送电子邮件,而不是将电子邮件存储在 ActionMailer::Base.deliveries-array 中(由用户观察者调用)...

你能告诉我为什么吗?

# Rails version
rails -v
=> Rails 3.0.1

# Ruby version with rvm (rvm version 1.0.16)
ruby -v
=> ruby 1.9.2p7 (2010-09-29 revision 29373) [x86_64-darwin10.4.0]

# Gemfile
gem "rspec-rails", ">= 2.0.1"

配置文件:

# config/environments/test.rb
MyApp::Application.configure do
  config.action_mailer.delivery_method = :test
  config.action_mailer.raise_delivery_errors = true
end

# spec/spec_helper.rb
...
ENV["RAILS_ENV"] ||= 'test'
...

# app/models/user_observer.rb
class UserObserver < ActiveRecord::Observer
  observe User

  def after_create(record)
    puts Rails.env
    # => "test"
    UserMailer.new_user_notification(record).deliver
    puts ActionMailer::Base.deliveries.inspect
    # => []
    # Sends it via smtp!
  end
end

【问题讨论】:

  • 您的测试环境中的 Mailer 配置是什么?

标签: ruby-on-rails email ruby-on-rails-3 rspec observer-pattern


【解决方案1】:

我太笨了...在我的 setup_mail.rb-initializer 中有“ActionMailer::Base.delivery_method = :smtp”... AAARGH ....

【讨论】:

  • 我遇到了同样的问题,我将该设置移至 config/environments/production.rb 并将其更改为 config.action_mailer.delivery_method = :smtp。感谢您发布您的答案并为我节省一些时间和调试;你绝对不傻:D
  • 你知道,世界上到处都是垃圾人……包括我!
【解决方案2】:

再详细说明一下这个问题的解决方法:

在您的 config/enviroments/test.rb 中,默认情况下您应该有 config.action_mailer.delivery_method = :test

这样做是告诉 ActionMailer 不要正常发送电子邮件,而是将发送的电子邮件存储在数组 ActionMailer::Base.deliveries 中。这对测试很有帮助,因为您可以通过使用 ActionMailer::Base.deliveries 数组上的 inspect、count、length 方法来判断已经发送了多少封电子邮件。

但是,如果您将交付方式设置为config.action_mailer.delivery_method = :smtp 之类的内容,则可能会覆盖您之前的交付方式 = :test;因此,您的 ActionMailer::Base.deliveries 将不会被填充。

我在使用 MailCatcher 查看正在发送的电子邮件时确实做到了这一点,从而导致我的测试失败,即使我确定电子邮件已正确发送!

因此,请确保您没有在测试环境中设置除 :test 之外的 delivery_method。

附带说明:如果您使用的是 Devise,则可能需要检查 Devise.mailer.deliveries 数组。

【讨论】:

    【解决方案3】:

    就我而言

    config.action_mailer.delivery_method = :test
    

    我也有

    config.action_mailer.perform_deliveries = false
    

    实际上(我想)不会发送电子邮件,也不会将其填充到 ActionMailer::Base.deliveries 数组中。

    【讨论】:

      【解决方案4】:

      另一个可能的问题......不要像我一样犯错误,包括

      ActionMailer::Base.delivery_method = :smtp
      

      在 config/environment.rb 中,我错误地认为它会被更具体的 config/environments/test.rb 覆盖。从 config/environment.rb 中删除上面的行为我解决了这个问题。

      【讨论】:

        【解决方案5】:

        就我而言,我忘记了spec.rb 中的.deliver 方法。然而,这很奇怪,即使没有它,我也从 Rails(Rails 5)获得了“电子邮件传递”的 STDOUT 消息,这非常令人困惑。看着你的规格让我意识到我忘记了。谢谢!

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-03-27
          • 2014-12-31
          • 2012-03-21
          • 2012-05-23
          • 1970-01-01
          • 1970-01-01
          • 2016-09-07
          相关资源
          最近更新 更多