How to test the content of Django emails?
I’m new to Django and I’m trying to check if there’s some text in the outbound email using
class test_send_daily_email(TestCase): def test_success(self): self.assertIn(mail.outbox.body, "My email's contents")
However, I’m having problems with
mail.outbox.body. It will output \
nMy email's contents\n and will not match the test text.
I tried several different fixes but none of them worked :
str(mail.outbox.body).rstrip()– Returns an identical string
str(mail.outbox.body).decode('utf-8')– attribute-free decoding
Sorry, I know this must be a trivial task. In Rails, I use something like Nokogiri to parse text. What is the correct way to parse this in Django? I can’t find instructions for this in the documentation
This depends on the actual content of your message (plain text or HTML), but the easy way to do this is to also encode the string you want to test.
# if you are testing HTML content self.assertTextInHTML("My email's contents", mail.outbox.body) # the string may need escaping the same way django escapes from django.utils.html import escape self.assertIn(escape("My email's contents"), mail.outbox.body)