You want to test a form that conditionally requires a phone number only if the user selects 'contact by phone'. How should you write the test to verify this conditional validation?
hard📝 Application Q8 of 15
Django - Testing Django Applications
You want to test a form that conditionally requires a phone number only if the user selects 'contact by phone'. How should you write the test to verify this conditional validation?
ASubmit form data with 'contact_method' set to 'phone' and empty 'phone' field, then assert form.is_valid() is False
BSubmit form data with 'contact_method' set to 'email' and empty 'phone' field, then assert form.is_valid() is False
CSubmit form data with 'contact_method' set to 'phone' and filled 'phone' field, then assert form.is_valid() is False
DSubmit form data with 'contact_method' set to 'email' and filled 'phone' field, then assert form.is_valid() is False
Step-by-Step Solution
Solution:
Step 1: Understand conditional requirement
Phone number is required only if 'contact_method' is 'phone'.
Step 2: Test missing phone when contact_method is phone
Submit data with 'contact_method'='phone' and empty 'phone' to check validation fails.
Final Answer:
Submit form data with 'contact_method' set to 'phone' and empty 'phone' field, then assert form.is_valid() is False -> Option A
Quick Check:
Conditional validation fails if required field missing [OK]
Quick Trick:Test conditional fields by submitting missing required data for that condition [OK]
Common Mistakes:
MISTAKES
Testing missing phone when contact_method is email
Expecting form to be invalid when phone is filled
Ignoring conditional logic in tests
Master "Testing Django Applications" in Django
9 interactive learning modes - each teaches the same concept differently