Thử nghiệm bố trí render trong khi gửi email có thể được thực hiện như một phần của các cuộc thử nghiệm điều khiển sử dụng assert_template
.
Với lớp bưu phẩm sau đây và phương pháp,
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
mật khẩu email đặt lại sẽ được trả lại bằng my_layout.html.erb
bố trí.
phương pháp bưu phẩm này có khả năng được áp dụng trong một phương pháp UsersController
, ví dụ:
class UsersController < ApplicationController
def forgot_password
user = ...
Notifier.password_reset_instructions(user).deliver_now
end
end
Các assert_template layout: "my_layout"
tuyên bố trong các thử nghiệm điều khiển sau cho users_controller#forgot_password
sẽ xác minh bố trí sử dụng:
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
Các các phần liên quan từ nhật ký:
Started POST "https://stackoverflow.com/users/forgot_password"
Processing by UsersController#forgot_password as HTML
...
Rendered notifier/password_reset_instructions.html.erb within layouts/my_layout (1.1ms)
Tài liệu tham khảo:
- Action Mailer Basics
- Testing Your Mailers - Functional Testing
- assert_template method
Nguồn
2015-05-09 12:55:32
Hey Luke. Điều gì về một khẳng định mà làm cho các mẫu với một bố trí thiết lập một cách rõ ràng, và so sánh các văn bản hoặc HTML để những gì được tạo ra (với bất kỳ bố trí hiện đang được chỉ định)? Suy nghĩ của tôi là nếu ai đó thay đổi giá trị bố trí trong bưu phẩm sau đó, kiểm tra sẽ thất bại. Không thử điều này, nhưng tôi đã đọc bài kiểm tra này và có ý tưởng đó: https://github.com/rails/rails/blob/master/actionmailer/test/base_test.rb#L545 Điều đó đang được nói, có vẻ như ở đó phải là một biến mẫu với tên bố cục được chôn ở đâu đó mà bạn có thể kiểm tra (hoặc thêm nó dưới dạng bản vá). –