-
-
Save fgrehm/5423117 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
en: | |
activemodel: | |
errors: | |
messages: | |
invalid_url: "must be a valid URL" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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