Testing Email functionality in Django serializer

11 views Asked by At

I have implemented this simple email feature in my serializer, that sends an email after a successful submission of a form

def create(
        self,
        validated_data,
    ):
        user = self.context["user"]
        profile_fields = ("owner_email", "owner_name", "phone_number", "cohort")
        profile_kwargs = {}

        for field in profile_fields:
            profile_kwargs[field] = self.initial_data.get(field) if field in self.initial_data else None

        if "solution" in validated_data:
            validated_data["specific_solution"] = validated_data.pop("solution")

        self._update_user_profile(user, **profile_kwargs)
        
        email_message = f"... some email message"
        
        send_mail(
            "Submission successful",
            email_message,
            settings.EMAIL_HOST_USER,
            [user.email],
            fail_silently=True,
        )


        return super().create(validated_data)

however, I have a failing test from the same implementation, here is the code snippet of the test

@patch('django.core.mail.send_mail')
    def test_email_sent_on_idea_submission(self, mock_send_email):
        self.assertEqual(len(mail.outbox), 0)  # Ensure no emails have been sent yet
       

        idea_data = self.ideas_data[0]
        idea_data["owner"] = idea_data["owner"].id
        idea_data["competition"] = idea_data["competition"].id

        serializer = IdeaSerializer(data=idea_data, context={"user": self.user})
        self.assertTrue(serializer.is_valid())
        serializer.save()
        
        print("Mail:", mail.outbox)
        
     
        
        self.assertEqual(len(mail.outbox), 1)

here is the error message from my terminal

=========================== short test summary info ============================
FAILED ideas/tests/test_serializers.py::IdeasSerializerTest::test_email_sent_on_idea_submission - AssertionError: 0 != 1

Apparently the test isn't sending an email after the serializer.save() although my actual implementation is, hence I'm having this assertion error AssertionError: 0 != 1. Please I need help guys

0

There are 0 answers