diff --git a/lib/validators/at_least_one_group_validator.rb b/lib/validators/at_least_one_group_validator.rb index 85071fdaf2c..d168ee4d491 100644 --- a/lib/validators/at_least_one_group_validator.rb +++ b/lib/validators/at_least_one_group_validator.rb @@ -3,13 +3,25 @@ class AtLeastOneGroupValidator def initialize(opts = {}) @opts = opts + @invalid_groups = [] end def valid_value?(val) - val.present? && val != "" + @invalid_groups = [] + + return false if val.blank? + + group_ids = val.to_s.split("|").map(&:to_i) + + @invalid_groups = group_ids - Group.where(id: group_ids).pluck(:id) + @invalid_groups.empty? end def error_message - I18n.t("site_settings.errors.at_least_one_group_required") + if @invalid_groups.empty? + I18n.t("site_settings.errors.at_least_one_group_required") + else + I18n.t("site_settings.errors.invalid_group") + end end end diff --git a/spec/lib/validators/at_least_one_group_validator_spec.rb b/spec/lib/validators/at_least_one_group_validator_spec.rb new file mode 100644 index 00000000000..00cf3c0c81d --- /dev/null +++ b/spec/lib/validators/at_least_one_group_validator_spec.rb @@ -0,0 +1,37 @@ +# frozen_string_literal: true + +RSpec.describe AtLeastOneGroupValidator do + subject(:validator) { described_class.new } + + describe "#valid_value?" do + context "when using a blank value" do + it { expect(validator.valid_value?(nil)).to eq(false) } + end + + context "when one of the groups doesn't exist" do + it { expect(validator.valid_value?("10|1337")).to eq(false) } + end + + context "when all the groups exist" do + it { expect(validator.valid_value?("10|11")).to eq(true) } + end + end + + describe "#error_message" do + context "when using a blank value" do + before { validator.valid_value?(nil) } + + it do + expect(validator.error_message).to eq( + "You must specify at least one group for this setting.", + ) + end + end + + context "when one of the groups doesn't exist" do + before { validator.valid_value?("10|1337") } + + it { expect(validator.error_message).to eq("There's no group with that name.") } + end + end +end