Skip to content

Instantly share code, notes, and snippets.

@fgrehm fgrehm/en.yml forked from leemachin/url_validator.rb
Last active Dec 16, 2015

Embed
What would you like to do?
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
You can’t perform that action at this time.