From 0db27b87183e239ca0263417e4640873489880bb Mon Sep 17 00:00:00 2001 From: simon lehericey Date: Tue, 31 May 2022 11:21:57 +0200 Subject: [PATCH] validate conditions on revision --- app/models/procedure_revision.rb | 12 +++++++ spec/models/procedure_revision_spec.rb | 45 ++++++++++++++++++++++++++ 2 files changed, 57 insertions(+) diff --git a/app/models/procedure_revision.rb b/app/models/procedure_revision.rb index 4b1e40914..146f3b4f8 100644 --- a/app/models/procedure_revision.rb +++ b/app/models/procedure_revision.rb @@ -30,6 +30,8 @@ class ProcedureRevision < ApplicationRecord scope :ordered, -> { order(:created_at) } + validate :conditions_are_valid? + def build_champs types_de_champ_public.map { |tdc| tdc.build_champ(revision: self) } end @@ -465,4 +467,14 @@ class ProcedureRevision < ApplicationRecord last.present? ? last.position + 1 : 0 end end + + def conditions_are_valid? + stable_ids = types_de_champ_public.map(&:stable_id) + + types_de_champ_public + .map.with_index + .filter_map { |tdc, i| tdc.condition.present? ? [tdc, i] : nil } + .flat_map { |tdc, i| tdc.condition.errors(stable_ids.take(i)) } + .each { |message| errors.add(:condition, message) } + end end diff --git a/spec/models/procedure_revision_spec.rb b/spec/models/procedure_revision_spec.rb index 54e0a38e4..2ac3d6e69 100644 --- a/spec/models/procedure_revision_spec.rb +++ b/spec/models/procedure_revision_spec.rb @@ -623,4 +623,49 @@ describe ProcedureRevision do end end end + + describe 'conditions_are_valid' do + include Logic + + def first_champ = procedure.draft_revision.types_de_champ_public.first + + def second_champ = procedure.draft_revision.types_de_champ_public.second + + let(:procedure) { create(:procedure, :with_type_de_champ, types_de_champ_count: 2) } + let(:draft_revision) { procedure.draft_revision } + let(:condition) { nil } + + subject do + draft_revision.save + draft_revision.errors + end + + before { second_champ.update(condition: condition) } + + context 'when a champ has a valid condition (type)' do + let(:condition) { ds_eq(constant(true), constant(true)) } + + it { is_expected.to be_empty } + end + + context 'when a champ has a valid condition: needed tdc is up in the forms' do + let(:condition) { ds_eq(constant('oui'), champ_value(first_champ.stable_id)) } + + it { is_expected.to be_empty } + end + + context 'when a champ has an invalid condition' do + let(:condition) { ds_eq(constant(true), constant(1)) } + + it { expect(subject.first.attribute).to eq(:condition) } + end + + context 'when a champ has an invalid condition: needed tdc is down in the forms' do + let(:need_second_champ) { ds_eq(constant('oui'), champ_value(second_champ.stable_id)) } + + before { first_champ.update(condition: need_second_champ) } + + it { expect(subject.first.attribute).to eq(:condition) } + end + end end