diff --git a/app/models/type_de_champ.rb b/app/models/type_de_champ.rb index 79aee06b4..33cfd914a 100644 --- a/app/models/type_de_champ.rb +++ b/app/models/type_de_champ.rb @@ -59,6 +59,17 @@ class TypeDeChamp < ApplicationRecord before_validation :check_mandatory before_save :remove_piece_justificative_template, if: -> { type_champ_changed? } + def valid?(context = nil) + super + if dynamic_type.present? + dynamic_type.valid? + errors.merge!(dynamic_type.errors) + end + errors.empty? + end + + alias_method :validate, :valid? + def set_dynamic_type @dynamic_type = type_champ.present? ? self.class.type_champ_to_class_name(type_champ).constantize.new(self) : nil end diff --git a/app/models/types_de_champ/type_de_champ_base.rb b/app/models/types_de_champ/type_de_champ_base.rb index a04f9d862..a7053dc38 100644 --- a/app/models/types_de_champ/type_de_champ_base.rb +++ b/app/models/types_de_champ/type_de_champ_base.rb @@ -1,4 +1,6 @@ class TypesDeChamp::TypeDeChampBase + include ActiveModel::Validations + def initialize(type_de_champ) @type_de_champ = type_de_champ end diff --git a/spec/models/type_de_champ_shared_example.rb b/spec/models/type_de_champ_shared_example.rb index f23cf2156..092527bbc 100644 --- a/spec/models/type_de_champ_shared_example.rb +++ b/spec/models/type_de_champ_shared_example.rb @@ -79,5 +79,26 @@ shared_examples 'type_de_champ_spec' do end end end + + context 'delegate validation to dynamic type' do + subject { build(:type_de_champ_text) } + let(:dynamic_type) do + Class.new(TypesDeChamp::TypeDeChampBase) do + validate :never_valid + + def never_valid + errors.add(:troll, 'always invalid') + end + end.new(subject) + end + + before { subject.instance_variable_set(:@dynamic_type, dynamic_type) } + + it { is_expected.to be_invalid } + it do + subject.validate + expect(subject.errors.full_messages.to_sentence).to eq('Troll always invalid') + end + end end end