3

If I have a model called Enquiry with an attribute of email how might I check that creating an Enquiry with an invalid email raises an error?

I have tried this

def test_email_is_valid(self):
    self.assertRaises(ValidationError, Enquiry.objects.create(email="testtest.com"))

However I get the Error

TypeError: 'Enquiry' object is not callable

I'm not quite getting something, does anybody know the correct method to test for email validation?

1 Answer 1

8

Django does not automatically validate objects when you call save() or create(). You can trigger validation by calling the full_clean method.

def test_email_is_valid(self):
    enquiry = Enquiry(email="testtest.com")
    self.assertRaises(ValidationError, enquiry.full_clean)

Note that you don't call full_clean() in the above code. You might prefer the context manager approach instead:

def test_email_is_valid(self):
    with self.assertRaises(ValidationError):
        enquiry = Enquiry(email="testtest.com")
        enquiry.full_clean()
Sign up to request clarification or add additional context in comments.

1 Comment

ValidationError can be imported with from django.core.exceptions import ValidationError

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.