language_validator_spec.rb 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. # frozen_string_literal: true
  2. require 'rails_helper'
  3. RSpec.describe LanguageValidator do
  4. let(:record_class) do
  5. Class.new do
  6. include ActiveModel::Validations
  7. attr_accessor :locale
  8. validates :locale, language: true
  9. end
  10. end
  11. let(:record) { record_class.new }
  12. describe '#validate_each' do
  13. context 'with a nil value' do
  14. it 'does not add errors' do
  15. record.locale = nil
  16. expect(record).to be_valid
  17. expect(record.errors).to be_empty
  18. end
  19. end
  20. context 'with an array of values' do
  21. it 'does not add errors with array of existing locales' do
  22. record.locale = %w(en fr)
  23. expect(record).to be_valid
  24. expect(record.errors).to be_empty
  25. end
  26. it 'adds errors with array having some non-existing locales' do
  27. record.locale = %w(en fr missing)
  28. expect(record).to_not be_valid
  29. expect(record.errors.first.attribute).to eq(:locale)
  30. expect(record.errors.first.type).to eq(:invalid)
  31. end
  32. end
  33. context 'with a locale string' do
  34. it 'does not add errors when string is an existing locale' do
  35. record.locale = 'en'
  36. expect(record).to be_valid
  37. expect(record.errors).to be_empty
  38. end
  39. it 'adds errors when string is non-existing locale' do
  40. record.locale = 'missing'
  41. expect(record).to_not be_valid
  42. expect(record.errors.first.attribute).to eq(:locale)
  43. expect(record.errors.first.type).to eq(:invalid)
  44. end
  45. end
  46. end
  47. end