提供電子郵件,我們有一個Rails控制器發送電子郵件:Rails的控制器不測試與ActiveMailer
class UsersController
def invite
mail = WeeklyReport.weekly_report(current_user).deliver
flash[:notice] = "Mail sent!"
redirect_to controller: "partners", action: "index"
end
end
class WeeklyReport < ActionMailer::Base
def weekly_report(recipient)
@data = recipient.data
mail(:to => "#{recipient.name} <#{recipient.email}>", :subject => "Weekly report")
end
end
當手動測試控制器,它實際上是發送電子郵件。但CONTROLER測試失敗:
it "should send mail" do
get :invite
response.should redirect_to "/partners/index"
request.flash[:notice].should eql("Mail sent!")
deliveries.size.should == 1 ### TEST FAILS HERE!
last_email.subject.should == "Weekly report"
last_email.to[0].should == '[email protected]'
end
# Failure/Error: deliveries.size.should == 1
# expected: 1
# got: 0 (using ==)
我的測試ENV配置是否正確: config.action_mailer.delivery_method = :test
而且WeeklyReport測試工作正常:
it "should send weekly report correctly" do
@user = FactoryGirl.create_list(:user)
email = WeeklyReport.weekly_report(@user).deliver
deliveries.size.should == 1
end
爲什麼控制器測試失敗?
編輯1: 我注意到郵件真的被交付(實際電子郵件),忽略了配置:config.action_mailer.delivery_method =:測試 - 什麼會是什麼?
編輯2: 我test.rb文件:
config.cache_classes = true
config.eager_load = false
config.serve_static_assets = true
config.static_cache_control = "public, max-age=3600"
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
config.action_mailer.default_url_options = { :host => 'dev.mydomain.com' }
config.action_dispatch.show_exceptions = false
config.action_controller.allow_forgery_protection = false
config.active_record.default_timezone = :local
config.action_mailer.delivery_method = :test
config.active_support.deprecation = :stderr
你在終端上遇到什麼錯誤? – Mandeep
沒有錯誤,只測試失敗的消息:失敗/錯誤:deliveries.size.should == 1 預計:1 得到:0(使用==) –
檢查您的'current_user'是否已設置並具有所有必填字段。看起來你的郵件程序默默無聞。在旁註中,即使它可以幫助您解決問題,但由於代碼重複,我完全不鼓勵您以這種方式進行測試。 – wicz