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?

Sayse
  • 42,633
  • 14
  • 77
  • 146
Reiss Johnson
  • 1,419
  • 1
  • 13
  • 19

1 Answers1

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()
Braiam
  • 1
  • 11
  • 47
  • 78
Alasdair
  • 298,606
  • 55
  • 578
  • 516