我遇到了在控制器(服务/ lib目录下的类)之外呈现HTML模板的情况,并且正在使用以下代码呈现模板。
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" })
通过使用调用实例方法的类,错误消失了。
答案 0 :(得分:0)
ActionController.render是一种经过良好测试的方法。 Rails核心团队看到了这一点。无需测试它是否按照其声明的方式进行操作。
相反,您要做的是确保使用正确的参数使用模拟对象调用ActionController.render
,如下所示:
describe SomeClass do
subject(:some_class) { described_class.new }
describe '#some_method' do
let(:template) { 'template' }
let(:layout) { 'mailer_template' }
before do
allow(ActionController).to receive(:render)
some_class.some_method
end
it 'renders the correct template' do
expect(ActionController)
.to have_received(:render)
.with({ template: template, layout: layout })
end
end
end
编辑
鉴于编辑后的帖子,这是我进行测试的方式。请注意,您的send_batch_email
方法中的所有代码都不在您的编辑中可见。因此,YMMV:
describe BatchSendingService do
subject(:batch_sending_service) { described_class.new }
describe '#send_batch_email' do
subject(:send_batch_email) do
batch_sending_service.send_batch_email(email, domain)
end
let(:email) { 'email' }
let(:domain) { 'domain' }
let(:batch_message) do
instance_double(
Mailgun::BatchMessage,
from: true,
body_html: true,
add_recipient, true,
finalize: true
)
end
let(:template) { 'send_batch_template' }
let(:layout) { 'layout' }
before do
allow(Mailgun::Client).to receive(:new)
allow(Mailgun::BatchMessage)
.to receive(:new)
.and_return(batch_message)
allow(batch_sending_service)
.to receive(:render)
send_batch_email
end
it 'renders the correct template' do
expect(batch_sending_service)
.to have_received(:render)
.with(template, layout)
end
end
end