我有一些Action Mailer电子邮件,我想测试将使用哪种布局来呈现电子邮件。我找到了this example on the web,但它是从2008年开始的,并不适用于Rails 3.2和大概以后的版本。
我的动机是,我想写一个单元测试,断言邮件是用特定的布局渲染的,所以如果改变了,测试就会中断。
答案 0 :(得分:3)
ActionController::TestCase
有一个方法assert_template
,所以这样的事情应该有效:
class MailerTest < ActionController::TestCase
...
def test_layout
assert_template layout: "layout/something"
end
...
end
答案 1 :(得分:2)
在发送电子邮件时测试呈现的布局可以使用assert_template
作为控制器测试的一部分来完成。
鉴于以下邮件程序类和方法,
class Notifier < ActionMailer::Base
def password_reset_instructions(user)
@user = user
@reset_password_link = ...
mail(to: ..., from: ...., subject: "Password Reset Instructions") do |format|
format.html {render layout: 'my_layout'}
format.text
end
end
end
密码重置电子邮件将使用my_layout.html.erb
布局呈现。
这种邮件程序方法很可能以UsersController
方法调用,例如:
class UsersController < ApplicationController
def forgot_password
user = ...
Notifier.password_reset_instructions(user).deliver_now
end
end
assert_template layout: "my_layout"
的以下控制器测试中的users_controller#forgot_password
语句将验证所使用的布局:
class UsersControllerTest < ActionController::TestCase
test "forgot password" do
assert_difference 'ActionMailer::Base.deliveries.size', +1 do
post :forgot_password, email: @user.email
end
assert_response :redirect
assert_template layout: "my_layout"
assert_template "password_reset_instructions"
password_reset_email = ActionMailer::Base.deliveries.last
assert_equal "Password Reset Instructions", password_reset_email.subject
end
end
日志中的相关部分:
Started POST "/users/forgot_password"
Processing by UsersController#forgot_password as HTML
...
Rendered notifier/password_reset_instructions.html.erb within layouts/my_layout (1.1ms)
参考文献: