existing_username_validator_spec.rb 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. # frozen_string_literal: true
  2. require 'rails_helper'
  3. describe ExistingUsernameValidator do
  4. let(:record_class) do
  5. Class.new do
  6. include ActiveModel::Validations
  7. attr_accessor :contact, :friends
  8. def self.name
  9. 'Record'
  10. end
  11. validates :contact, existing_username: true
  12. validates :friends, existing_username: { multiple: true }
  13. end
  14. end
  15. let(:record) { record_class.new }
  16. describe '#validate_each' do
  17. context 'with a nil value' do
  18. it 'does not add errors' do
  19. record.contact = nil
  20. expect(record).to be_valid
  21. expect(record.errors).to be_empty
  22. end
  23. end
  24. context 'when there are no accounts' do
  25. it 'adds errors to the record' do
  26. record.contact = 'user@example.com'
  27. expect(record).to_not be_valid
  28. expect(record.errors.first.attribute).to eq(:contact)
  29. expect(record.errors.first.type).to eq I18n.t('existing_username_validator.not_found')
  30. end
  31. end
  32. context 'when there are accounts' do
  33. before { Fabricate(:account, domain: 'example.com', username: 'user') }
  34. context 'when the value does not match' do
  35. it 'adds errors to the record' do
  36. record.contact = 'friend@other.host'
  37. expect(record).to_not be_valid
  38. expect(record.errors.first.attribute).to eq(:contact)
  39. expect(record.errors.first.type).to eq I18n.t('existing_username_validator.not_found')
  40. end
  41. context 'when multiple is true' do
  42. it 'adds errors to the record' do
  43. record.friends = 'friend@other.host'
  44. expect(record).to_not be_valid
  45. expect(record.errors.first.attribute).to eq(:friends)
  46. expect(record.errors.first.type).to eq I18n.t('existing_username_validator.not_found_multiple', usernames: 'friend@other.host')
  47. end
  48. end
  49. end
  50. context 'when the value does match' do
  51. it 'does not add errors to the record' do
  52. record.contact = 'user@example.com'
  53. expect(record).to be_valid
  54. expect(record.errors).to be_empty
  55. end
  56. context 'when multiple is true' do
  57. it 'does not add errors to the record' do
  58. record.friends = 'user@example.com'
  59. expect(record).to be_valid
  60. expect(record.errors).to be_empty
  61. end
  62. end
  63. end
  64. end
  65. end
  66. end