url_validator_spec.rb 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. # frozen_string_literal: true
  2. require 'rails_helper'
  3. describe URLValidator do
  4. let(:record_class) do
  5. Class.new do
  6. include ActiveModel::Validations
  7. attr_accessor :profile
  8. validates :profile, url: 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 'adds errors' do
  15. record.profile = nil
  16. expect(record).to_not be_valid
  17. expect(record.errors.first.attribute).to eq(:profile)
  18. expect(record.errors.first.type).to eq(:invalid)
  19. end
  20. end
  21. context 'with an invalid url scheme' do
  22. it 'adds errors' do
  23. record.profile = 'ftp://example.com/page'
  24. expect(record).to_not be_valid
  25. expect(record.errors.first.attribute).to eq(:profile)
  26. expect(record.errors.first.type).to eq(:invalid)
  27. end
  28. end
  29. context 'without a hostname' do
  30. it 'adds errors' do
  31. record.profile = 'https:///page'
  32. expect(record).to_not be_valid
  33. expect(record.errors.first.attribute).to eq(:profile)
  34. expect(record.errors.first.type).to eq(:invalid)
  35. end
  36. end
  37. context 'with an unparseable value' do
  38. it 'adds errors' do
  39. record.profile = 'https://host:port/page' # non-numeric port string causes invalid uri error
  40. expect(record).to_not be_valid
  41. expect(record.errors.first.attribute).to eq(:profile)
  42. expect(record.errors.first.type).to eq(:invalid)
  43. end
  44. end
  45. context 'with a valid url' do
  46. it 'does not add errors' do
  47. record.profile = 'https://example.com/page'
  48. expect(record).to be_valid
  49. expect(record.errors).to be_empty
  50. end
  51. end
  52. end
  53. end