Created
July 20, 2012 15:02
-
-
Save leemeichin/3151191 to your computer and use it in GitHub Desktop.
Rails Custom URL Validator
This file contains 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) | |
record.errors[attribute] << (options[:message] || "must be a valid URL") unless url_valid?(value) | |
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 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 do | |
@validator = UrlValidator.new attributes: {} | |
end | |
context 'invalid input' do | |
it 'should return false for a poorly formed URL' do | |
@validator.url_valid?('something.com').should be_false | |
end | |
it 'should return false for garbage input' do | |
pi = 3.14159265 | |
@validator.url_valid?(pi).should be_false | |
end | |
it 'should return false for URLs without an HTTP protocol' do | |
@validator.url_valid?('ftp://secret-file-stash.net').should be_false | |
end | |
end | |
context 'valid input' do | |
it 'should return true for a correctly formed HTTP URL' do | |
@validator.url_valid?('http://nooooooooooooooo.com').should be_true | |
end | |
it 'should return true for a correctly formed HTTPS URL' do | |
@validator.url_valid?('https://google.com').should be_true | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Trying to run with Rails 4 as is, test fails with -
Fix -