【发布时间】:2018-12-05 18:09:56
【问题描述】:
我有一种情况要在控制器之外渲染一个 HTML 模板(service/lib 目录下的一个类),我正在使用下面的代码渲染模板。
class SomeClass
def some_method
@template = ApplicationController.render(
template: 'template',
layout: mailer_template,
)
end
end
有什么方法可以测试渲染的模板是否是预期的模板,以及在该方法调用期间是否发生了渲染?
编辑
class BatchSendingService < AbstractController::Base
require 'abstract_controller'
include AbstractController::Rendering
include AbstractController::AssetPaths
include AbstractController::Helpers
include Rails.application.routes.url_helpers
include ActionView::Rendering
include ActionView::ViewPaths
include ActionView::Layouts
self.view_paths = "app/views"
def send_batch_email(mail, domain)
@project = mail.project
@client = Mailgun::Client.new ENV['MAILGUN_API_KEY']
batch_message = Mailgun::BatchMessage.new(@client, domain)
batch_message.from(from_data)
mailer_layout = get_mailer_layout(mail.layout)
mail_html = render(
template: 'send_batch_email',
layout: mailer_layout
)
batch_message.body_html(mail_html.to_s)
batch_message.add_recipient(:to, recipient_email, {})
response = batch_message.finalize
end
编辑
obj= BatchSendingService.new
allow(obj).to receive(:render)
BatchSendingService.send_batch_email(mail, domain)
expect(obj) .to have_received(:render)
.with({ template: "template", layout: "layout" })
通过使用调用实例方法的类,错误消失了。
【问题讨论】:
-
正在渲染的布局/模板中有太多本地和其他样式。因此,如果我能够检查调用方法是否呈现了布局,那就太好了。您能解释一下如何使用邮件规范进行测试吗?仅供参考:此方法发送批量发送 API。
标签: ruby-on-rails rspec ruby-on-rails-5 rspec-rails renderer