如果发送电子邮件,如何使用 RSpec 进行测试 [英] How to test with RSpec if an email is delivered
问题描述
如果我使用 :post 调用控制器方法,我想测试是否发送了电子邮件.我将使用 email_spec 所以我在这里尝试了这个:http://rubydoc.info/gems/email_spec/1.2.1/file/README.rdoc#Testing_In_Isolation
I'd like to test if an email is delivered if I call a controller method with :post. I'll use email_spec so I tried this snipped here: http://rubydoc.info/gems/email_spec/1.2.1/file/README.rdoc#Testing_In_Isolation
但它不起作用,因为我将模型对象的一个实例传递给了交付方法,并且该实例在交付之前已保存.
But it doesn't work, because I pass an instance of the model-object to the delivery-method and the instance is saved before the delivery.
我尝试创建模型对象的另一个实例,但 ID 不相同.
I tried to create an other instance of the model-object, but then the id isn't the same.
我的控制器方法如下所示:
My controller-method looks like this:
def create
@params = params[:reservation]
@reservation = Reservation.new(@params)
if @reservation.save
ReservationMailer.confirm_email(@reservation).deliver
redirect_to success_path
else
@title = "Reservation"
render 'new'
end
end
你有什么办法解决这个问题吗?
Do you have any idea to solve this?
推荐答案
假设您的测试环境以通常的方式设置(即,您有 config.action_mailer.delivery_method = :test
),然后将发送的电子邮件作为 Mail::Message
实例插入到全局数组 ActionMailer::Base.deliveries
中.您可以从测试用例中读取该信息并确保电子邮件符合预期.请参阅此处.
Assuming your test environment is set up in the usual fashion (that is, you have config.action_mailer.delivery_method = :test
), then delivered emails are inserted into the global array ActionMailer::Base.deliveries
as Mail::Message
instances. You can read that from your test case and ensure the email is as expected. See here.
这篇关于如果发送电子邮件,如何使用 RSpec 进行测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!