diff --git a/app/models/case_log.rb b/app/models/case_log.rb index 1f8743b9f..4bc71db3f 100644 --- a/app/models/case_log.rb +++ b/app/models/case_log.rb @@ -49,6 +49,31 @@ class CaseLogValidator < ActiveModel::Validator end end + def validate_household_pregnancy(record) + if (record.pregnancy == "Yes" || record.pregnancy == "Prefer not to say") && !women_of_child_bearing_age_in_household(record) + record.errors.add :pregnancy, "You must answer no as there are no female tenants aged 16-50 in the property" + end + end + + def women_of_child_bearing_age_in_household(record) + unless record.tenant_gender.nil? || record.tenant_age.nil? + if record.tenant_gender == "Female" && record.tenant_age >= 16 && record.tenant_age <= 50 + return true + end + end + + p = 2 + while p <= 8 + unless record["person_#{p}_gender"].nil? || record["person_#{p}_age"].nil? + if record["person_#{p}_gender"] == "Female" && record["person_#{p}_age"] >= 16 && record["person_#{p}_age"] <= 50 + return true + end + end + p += 1 + end + return false + end + def validate(record) # If we've come from the form UI we only want to validate the specific fields # that have just been submitted. If we're submitting a log via API or Bulk Upload diff --git a/spec/features/case_log_spec.rb b/spec/features/case_log_spec.rb index 3e16f8530..e915e97a6 100644 --- a/spec/features/case_log_spec.rb +++ b/spec/features/case_log_spec.rb @@ -93,6 +93,38 @@ RSpec.describe "Test Features" do ) end + context "Validate pregnancy questions" do + it "Cannot answer yes if no female tenants" do + expect { + CaseLog.create!(pregnancy: "Yes", tenant_gender: "Male", tenant_age: 20) + }.to raise_error(ActiveRecord::RecordInvalid) + end + + it "Cannot answer yes if no female tenants within age range" do + expect { + CaseLog.create!(pregnancy: "Yes", tenant_gender: "Female", tenant_age: 51) + }.to raise_error(ActiveRecord::RecordInvalid) + end + + it "Cannot answer prefer not to say if no valid tenants" do + expect { + CaseLog.create!(pregnancy: "Prefer not to say", tenant_gender: "Male", tenant_age: 20) + }.to raise_error(ActiveRecord::RecordInvalid) + end + + # it "Can answer yes if valid tenants" do + # expect { + # CaseLog.create!(pregnancy: "Yes", tenant_gender: "Female", tenant_age: 20) + # }.to raise_error(ActiveRecord::RecordInvalid) + # end + + # it "Can answer yes if valid second tenant" do + # expect { + # CaseLog.create!(pregnancy: "Yes", tenant_gender: "Male", tenant_age: 99, person_2_gender: "Female", person_2_age: 20) + # }.to raise_error(ActiveRecord::RecordInvalid) + # end + end + it "can be accessed by url" do visit("/case_logs/#{id}/tenant_age") expect(page).to have_field("case-log-tenant-age-field")