提供电子邮件,我们有一个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