为什么我的Rspec测试发送真实邮件?

时间:2012-03-15 15:36:09

标签: ruby-on-rails testing actionmailer

我教过这个,delivery_method = :test中有config/environments/test.rb这样的选项我在运行Rspec测试时不应收到任何邮件:

配置/环境/ test.rb:

config.action_mailer.delivery_method = :test

但是在我的测试中,当我使用FactoryGirl创建用户并且用户有after_save回调发送注册通知时,将发送此电子邮件:

myspec.rb:

user = FactoryGirl.create(:user, :login => 'johndoe')

user_observer.rb:

class UserObserver < ActiveRecord::Observer
  def after_create(user)
    UserMailer.signup_notification(user).deliver
  end
end

action_mailer.rb:

ActionMailer::Base.delivery_method = :smtp

ActionMailer::Base.smtp_settings = {
  :address => "...",
  :port => "25",
  :domain => "...",
  :user_name => "...",
  :password => "...",
  :authentication => :plain
}

有什么不对?

我正在使用:

  • Rails 3.2.2
  • buildin ActionMailer
  • RSpec的摆幅
  • FactoryGirl
  • 保护

1 个答案:

答案 0 :(得分:0)

是的,你是对的。 ActionMailer :: Base.delivery_method =:smtp屏蔽你在environment / test.rb中的配置

我建议您使用下一个解决方案:使用每个范围的特定数据创建夹具 就像在enter link description here中一样 在我的情况下,它看起来像:

我的config.yml

 development:
      support_mail: test@test.test
      smtp_user_name: test@test.test
      smtp_password: test
      smtp_domain: test.test
      smtp_address: test.test.test
      smtp_port: => 999

    test:
      support_mail: test@test.test
      smtp_user_name: test@test.test
      smtp_password: test
      smtp_domain: test.test
      smtp_address: test.test.test
      smtp_port: => 999

    production:
      support_mail: somth@somth.com
      smtp_user_name: somth@somth.com
      smtp_password: somth
      smtp_domain: somth.com
      smtp_address: smtp.somth.com
      smtp_port: => 587

my environment.rb

# Load the rails application
require File.expand_path('../application', __FILE__)
#initialize custom config variables
APP_CONFIG = YAML.load_file("#{Rails.root}/config/config.yml")[Rails.env]
    ActionMailer::Base.smtp_settings = {
      :user_name => APP_CONFIG["smtp_user_name"], #ENV['SENDGRID_USERNAME'],
      :password => APP_CONFIG["smtp_password"], #  ENV['SENDGRID_PASSWORD'],
      :domain => APP_CONFIG["smtp_domain"],
      :address => APP_CONFIG["smtp_address"],
      :port => APP_CONFIG["smtp_port"],
      :authentication => :plain,
      :enable_starttls_auto => false
    }
ActionMailer::Base.delivery_method = :smtp