DEV: Validate that passed in groups exist in AtLeastOneGroupValidator (#24890)

This validator is used for site settings where one or more groups are to be input.

At the moment this validator just checks that the value isn't blank. This PR adds a validation for the existence of the groups passed in.
This commit is contained in:
Ted Johansson 2023-12-14 10:00:53 +08:00 committed by GitHub
parent 48116186af
commit f029d8142b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 51 additions and 2 deletions

View File

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

View File

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