From b0aa8611d4d184950279b1c0b9112700979185fb Mon Sep 17 00:00:00 2001 From: baarkerlounger <5101747+baarkerlounger@users.noreply.github.com> Date: Tue, 9 Aug 2022 11:19:40 +0100 Subject: [PATCH] Fix checkbox validation (#823) * Don't crash when invalid checkbox answers are selected * Ensure all checkbox selections are preserved not just the first that doesn't match the all * Rubocop --- app/controllers/form_controller.rb | 5 +++-- spec/features/form/checkboxes_spec.rb | 23 +++++++++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/app/controllers/form_controller.rb b/app/controllers/form_controller.rb index 5a8d6375d..ad3f858e3 100644 --- a/app/controllers/form_controller.rb +++ b/app/controllers/form_controller.rb @@ -73,7 +73,7 @@ private end if session["fields"] session["fields"].each do |field, value| - unless @case_log.form.get_question(field, @case_log).type == "date" + unless @case_log.form.get_question(field, @case_log)&.type == "date" @case_log[field] = value end end @@ -161,10 +161,11 @@ private def question_missing_response?(responses_for_page, question) if %w[checkbox validation_override].include?(question.type) - question.answer_options.keys.reject { |x| x.match(/divider/) }.all? do |option| + answered = question.answer_options.keys.reject { |x| x.match(/divider/) }.map do |option| session["fields"][option] = @case_log[option] = params["case_log"][question.id].include?(option) ? 1 : 0 params["case_log"][question.id].exclude?(option) end + answered.all? else session["fields"][question.id] = @case_log[question.id] = responses_for_page[question.id] responses_for_page[question.id].nil? || responses_for_page[question.id].blank? diff --git a/spec/features/form/checkboxes_spec.rb b/spec/features/form/checkboxes_spec.rb index f6486906e..cbf5e51c1 100644 --- a/spec/features/form/checkboxes_spec.rb +++ b/spec/features/form/checkboxes_spec.rb @@ -38,4 +38,27 @@ RSpec.describe "Checkboxes" do expect(case_log["housingneeds_h"]).to eq(1) end end + + context "when a checkbox question is submitted with invalid answers" do + before do + allow(case_log).to receive(:update).and_return(false) + end + + it "shows an error summary" do + visit("/logs/#{id}/accessibility-requirements") + page.check("case-log-accessibility-requirements-housingneeds-a-field") + page.check("case-log-accessibility-requirements-housingneeds-c-field") + click_button("Save and continue") + expect(page).to have_title("Error") + end + + it "persists the original selections" do + visit("/logs/#{id}/accessibility-requirements") + page.check("case-log-accessibility-requirements-housingneeds-a-field") + page.check("case-log-accessibility-requirements-housingneeds-c-field") + click_button("Save and continue") + expect(page).to have_checked_field("case-log-accessibility-requirements-housingneeds-a-field") + expect(page).to have_checked_field("case-log-accessibility-requirements-housingneeds-c-field") + end + end end