[Solved]-How to test send_mail in Django?

16👍

Thanks for @Alasdair for the solution. Turns out it was quite simple. Just remove override_settings and import outbox.

tests.py

from django.core.mail import outbox

class UserModelTest(TestCase):
    def setUp(self):
        self.user = User.objects.create_user(email='user@info.com',
            password='0000')

    def test_send_password_token(self):
        """
        Sends a password reset mail with users authentication token.
        """
        token = Token.objects.get(user=self.user)
        User.send_password_token(self.user.email)
        self.assertEqual(len(outbox), 1)
        self.assertEqual(outbox[0].subject, 'Password reset:')
        self.assertEqual(outbox[0].from_email, <insert_from_email>)
        self.assertEqual(outbox[0].to, [<insert_list_of_to_emails>])
        self.assertEqual(outbox[0].body,
            'Your password reset token:\n\n\t%s' % token.key)

Leave a comment