From 3c9cc6c070007422d7b08cc3edbb8660da1ac6cf Mon Sep 17 00:00:00 2001 From: Paul Chavard Date: Wed, 8 Jul 2020 14:39:06 +0200 Subject: [PATCH] Remove repetition types_de_champ on type_champ change --- app/models/type_de_champ.rb | 7 +++++++ spec/factories/type_de_champ.rb | 6 ++++++ spec/models/type_de_champ_shared_example.rb | 14 ++++++++++++++ 3 files changed, 27 insertions(+) diff --git a/app/models/type_de_champ.rb b/app/models/type_de_champ.rb index 9887cf77d..0a1840110 100644 --- a/app/models/type_de_champ.rb +++ b/app/models/type_de_champ.rb @@ -83,6 +83,7 @@ class TypeDeChamp < ApplicationRecord before_validation :check_mandatory before_save :remove_piece_justificative_template, if: -> { type_champ_changed? } before_validation :remove_drop_down_list, if: -> { type_champ_changed? } + before_save :remove_repetition, if: -> { type_champ_changed? } def valid?(context = nil) super @@ -302,4 +303,10 @@ class TypeDeChamp < ApplicationRecord self.drop_down_options = nil end end + + def remove_repetition + if !repetition? + types_de_champ.destroy_all + end + end end diff --git a/spec/factories/type_de_champ.rb b/spec/factories/type_de_champ.rb index 7cf7c41a8..d04b7dd7f 100644 --- a/spec/factories/type_de_champ.rb +++ b/spec/factories/type_de_champ.rb @@ -108,6 +108,12 @@ FactoryBot.define do end factory :type_de_champ_repetition do type_champ { TypeDeChamp.type_champs.fetch(:repetition) } + + trait :with_types_de_champ do + after(:build) do |type_de_champ, _evaluator| + type_de_champ.types_de_champ << create(:type_de_champ, libelle: 'sub type de champ') + end + end end trait :private do diff --git a/spec/models/type_de_champ_shared_example.rb b/spec/models/type_de_champ_shared_example.rb index 2c0ba51ae..7f2e97b27 100644 --- a/spec/models/type_de_champ_shared_example.rb +++ b/spec/models/type_de_champ_shared_example.rb @@ -89,6 +89,20 @@ shared_examples 'type_de_champ_spec' do end end + context 'remove repetition' do + let(:tdc) { create(:type_de_champ_repetition, :with_types_de_champ) } + + before do + tdc.update_attribute('type_champ', target_type_champ) + end + + context 'when the target type_champ is not repetition' do + let(:target_type_champ) { TypeDeChamp.type_champs.fetch(:text) } + + it { expect(tdc.types_de_champ).to be_empty } + end + end + context 'delegate validation to dynamic type' do subject { build(:type_de_champ_text) } let(:dynamic_type) do