[#2258] Let dynamic type validate the type de champ

This commit is contained in:
Frederic Merizen 2018-09-11 18:54:27 +02:00
parent 695426316c
commit 3fea14c07d
3 changed files with 34 additions and 0 deletions

View file

@ -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

View file

@ -1,4 +1,6 @@
class TypesDeChamp::TypeDeChampBase
include ActiveModel::Validations
def initialize(type_de_champ)
@type_de_champ = type_de_champ
end

View file

@ -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