Add coverage for LanguageValidator (#25593)

This commit is contained in:
Matt Jankowski 2023-07-28 17:12:09 -04:00 committed by GitHub
parent ad81be6c8e
commit 6602edf064
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 68 additions and 6 deletions

View File

@ -4,18 +4,20 @@ class LanguageValidator < ActiveModel::EachValidator
include LanguagesHelper include LanguagesHelper
def validate_each(record, attribute, value) def validate_each(record, attribute, value)
record.errors.add(attribute, :invalid) unless valid?(value) @value = value
record.errors.add(attribute, :invalid) unless valid_locale_value?
end end
private private
def valid?(str) def valid_locale_value?
if str.nil? if @value.nil?
true true
elsif str.is_a?(Array) elsif @value.is_a?(Array)
str.all? { |x| valid_locale?(x) } @value.all? { |x| valid_locale?(x) }
else else
valid_locale?(str) valid_locale?(@value)
end end
end end
end end

View File

@ -0,0 +1,60 @@
# frozen_string_literal: true
require 'rails_helper'
describe LanguageValidator do
let(:record_class) do
Class.new do
include ActiveModel::Validations
attr_accessor :locale
validates :locale, language: true
end
end
let(:record) { record_class.new }
describe '#validate_each' do
context 'with a nil value' do
it 'does not add errors' do
record.locale = nil
expect(record).to be_valid
expect(record.errors).to be_empty
end
end
context 'with an array of values' do
it 'does not add errors with array of existing locales' do
record.locale = %w(en fr)
expect(record).to be_valid
expect(record.errors).to be_empty
end
it 'adds errors with array having some non-existing locales' do
record.locale = %w(en fr missing)
expect(record).to_not be_valid
expect(record.errors.first.attribute).to eq(:locale)
expect(record.errors.first.type).to eq(:invalid)
end
end
context 'with a locale string' do
it 'does not add errors when string is an existing locale' do
record.locale = 'en'
expect(record).to be_valid
expect(record.errors).to be_empty
end
it 'adds errors when string is non-existing locale' do
record.locale = 'missing'
expect(record).to_not be_valid
expect(record.errors.first.attribute).to eq(:locale)
expect(record.errors.first.type).to eq(:invalid)
end
end
end
end