ActionMailer::TestHelper 提供了一个类似于 Rake test 的测试方法 assert_emails,可以用来确保正确发送了电子邮件。下面是一个包含 assert_emails 测试方法的示例代码:
require 'test_helper'
class UserMailerTest < ActionMailer::TestCase
test 'confirmation_email should be sent to user' do
user = users(:one)
email = UserMailer.confirmation_email(user).deliver_now
assert_emails 1 do
email.deliver_now
end
assert_equal [user.email], email.to
assert_equal 'Confirmation Email', email.subject
assert_match 'Confirmation instructions', email.body.to_s
end
end
该测试方法接受一个块作为参数,该块中的代码应该会发送电子邮件。如果测试通过,assert_emails 将返回 true。如果电子邮件未成功发送,则会引发一个 AssertionError。