Skip to content

Instantly share code, notes, and snippets.

@fgrehm
Forked from leemeichin/url_validator.rb
Last active December 16, 2015 10:49
Show Gist options
  • Save fgrehm/5423117 to your computer and use it in GitHub Desktop.
Save fgrehm/5423117 to your computer and use it in GitHub Desktop.
en:
activemodel:
errors:
messages:
invalid_url: "must be a valid URL"
class UrlValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
unless url_valid?(value)
record.errors.add(attribute, options[:message] || :invalid_url)
end
end
# a URL may be technically well-formed but may not actually be
# valid, so this checks for both.
def url_valid?(url)
url = URI.parse(url) rescue false
url.kind_of?(URI::HTTP) || url.kind_of?(URI::HTTPS)
end
end
describe UrlValidator do
before { @validator = UrlValidator.new(attributes: {}) }
context 'invalid input' do
it 'should return false for a poorly formed URL' do
expect(@validator.url_valid? 'something.com').to be false
end
it 'should return false for garbage input' do
pi = 3.14159265
expect(@validator.url_valid? pi).to be false
end
it 'should return false for URLs without an HTTP protocol' do
expect(@validator.url_valid? 'ftp://secret-file-stash.net').to be false
end
end
context 'valid input' do
it 'should return true for a correctly formed HTTP URL' do
expect(@validator.url_valid? 'http://nooooooooooooooo.com').to be true
end
it 'should return true for a correctly formed HTTPS URL' do
expect(@validator.url_valid? 'https://google.com').to be true
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment