如果它们有效,则在开发中发送电子邮件以手动查看它们通常不是一种干净的测试方式。
这个 Rails 指南也涵盖了控制器的测试。为您的电子邮件设置测试非常简单(来自链接的Rails 指南):
#unit test
require 'test_helper'
class UserMailerTest < ActionMailer::TestCase
tests UserMailer
test "invite" do
@expected.from = 'me@example.com'
@expected.to = 'friend@example.com'
@expected.subject = "You have been invited by #{@expected.from}"
assert_equal @expected.encoded, UserMailer.create_invite('me@example.com', 'friend@example.com', @expected.date).encoded
end
end
和一个示例功能测试(也来自Rails Guide):
require 'test_helper'
class UserControllerTest < ActionController::TestCase
test "invite friend" do
assert_difference 'ActionMailer::Base.deliveries.size', +1 do
post :invite_friend, :email => 'friend@example.com'
end
invite_email = ActionMailer::Base.deliveries.last
assert_equal "You have been invited by me@example.com", invite_email.subject
assert_equal 'friend@example.com', invite_email.to[0]
assert_match(/Hi friend@example.com/, invite_email.body)
end
end