mirror of
https://github.com/discourse/discourse.git
synced 2024-11-22 11:15:05 +08:00
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:
parent
48116186af
commit
f029d8142b
|
@ -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
|
||||
|
|
37
spec/lib/validators/at_least_one_group_validator_spec.rb
Normal file
37
spec/lib/validators/at_least_one_group_validator_spec.rb
Normal 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
|
Loading…
Reference in New Issue
Block a user