Update validates_email_format_of plugin
authorTom Hughes <tom@compton.nu>
Fri, 3 Sep 2010 18:09:22 +0000 (19:09 +0100)
committerTom Hughes <tom@compton.nu>
Mon, 14 Nov 2011 09:42:43 +0000 (09:42 +0000)
19 files changed:
vendor/plugins/validates_email_format_of/.gitignore
vendor/plugins/validates_email_format_of/CHANGELOG.rdoc [moved from vendor/plugins/validates_email_format_of/CHANGELOG with 55% similarity]
vendor/plugins/validates_email_format_of/MIT-LICENSE
vendor/plugins/validates_email_format_of/README.markdown [deleted file]
vendor/plugins/validates_email_format_of/README.rdoc [new file with mode: 0644]
vendor/plugins/validates_email_format_of/Rakefile [deleted file]
vendor/plugins/validates_email_format_of/init.rb
vendor/plugins/validates_email_format_of/lib/validates_email_format_of.rb
vendor/plugins/validates_email_format_of/rails/init.rb [deleted file]
vendor/plugins/validates_email_format_of/rakefile.rb [new file with mode: 0644]
vendor/plugins/validates_email_format_of/shoulda_macros/validates_email_format_of.rb [deleted file]
vendor/plugins/validates_email_format_of/test/database.yml [new file with mode: 0644]
vendor/plugins/validates_email_format_of/test/db/email_format_test.sqlite3 [deleted file]
vendor/plugins/validates_email_format_of/test/fixtures/people.yml [new file with mode: 0644]
vendor/plugins/validates_email_format_of/test/fixtures/person.rb [new file with mode: 0644]
vendor/plugins/validates_email_format_of/test/schema.rb [new file with mode: 0644]
vendor/plugins/validates_email_format_of/test/test_helper.rb
vendor/plugins/validates_email_format_of/test/validates_email_format_of_test.rb
vendor/plugins/validates_email_format_of/validates_email_format_of.gemspec

index c5f93e3ef6dc3ebc69891ebd77fd28dce4674cf2..584362fd9511fcebd0e5f0c85a60f175ed847705 100644 (file)
@@ -1,3 +1,2 @@
 pkg
-test/debug.log
-*.swp
+test/debug.log
\ No newline at end of file
similarity index 55%
rename from vendor/plugins/validates_email_format_of/CHANGELOG
rename to vendor/plugins/validates_email_format_of/CHANGELOG.rdoc
index ce4a5e1580654dee9e21de19c5aec89d55b4807d..c0362074f22a75d17c64f852f3a32fbed653a442 100644 (file)
@@ -1,14 +1,19 @@
 = CHANGELOG
 
-== Version 1.0
- * initial version
+== Version 1.4.1 (the George Anderson and 'history' edition)
+ * don't allow domains with underscores
+ * removed extra spaces in validation messages
+ * updated tests for Rails 2.3+
 
-== Version 1.1 (the Francis Hwang edition)
- * moved Regexp out of class methods into the ValidatesEmailFormatOf module
+== Version 1.4 (the Denis Ahearn edition)
+ * added ability to run validation tests without touching ActiveRecord or a database
 
-== Version 1.2 (the Ismael Santos Kafeltz and Michael MacDonald edition)
- * added support for un-escaped and escaped special characters in the local part, per RFC 3696
- * added :allow_nil option
+== Version 1.3.1 (the Github edition)
+ * updated for github
+
+== Version 1.3 (the Travis Sinnott edition)
+ * added optional MX record check
+ * now available as a gem
 
 == Version 1.2.1 (the RTFM edition)
  * added support for quoted local parts
  * added :allow_blank option
  * added :unless option
 
-== Unreleased
- * Now available as a gem on GitHub
- * added should_validate_email_format_of
+== Version 1.2 (the Ismael Santos Kafeltz and Michael MacDonald edition)
+ * added support for un-escaped and escaped special characters in the local part, per RFC 3696
+ * added :allow_nil option
+
+== Version 1.1 (the Francis Hwang edition)
+ * moved Regexp out of class methods into the ValidatesEmailFormatOf module
+
+== Version 1.0
+ * initial version
index c94752595ecfd389565ef175080d896e392e6fee..badda6b787b1fcd20b7bbdcd346f2ed82a9c0e48 100644 (file)
@@ -1,4 +1,4 @@
-Copyright (c) 2006 Alex Dunae
+Copyright (c) 2006-09 Alex Dunae
 
 Permission is hereby granted, free of charge, to any person obtaining
 a copy of this software and associated documentation files (the
diff --git a/vendor/plugins/validates_email_format_of/README.markdown b/vendor/plugins/validates_email_format_of/README.markdown
deleted file mode 100644 (file)
index d432574..0000000
+++ /dev/null
@@ -1,58 +0,0 @@
-Validates email format
-======================
-
-Validate various formats of email address against RFC 2822.
-
-Usage
------
-  
-    class PersonTest < ActiveSupport::TestCase
-      should_validate_email_format_of :email
-    end
-
-    class Person < ActiveRecord::Base
-      validates_email_format_of :email
-    end
-
-Options
--------
-
-    :message =>
-      String. A custom error message (default is: " does not appear to be a valid e-mail address")
-
-    :on =>
-      Symbol. Specifies when this validation is active (default is :save, other options :create, :update)
-
-    :allow_nil =>
-      Boolean. Allow nil values (default is false)
-
-    :allow_blank =>
-      Boolean. Allow blank values (default is false)
-
-    :if =>
-      Specifies a method, proc or string to call to determine if the validation should occur 
-      (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The method, 
-      proc or string should return or evaluate to a true or false value. 
-
-    :unless =>
-      See :if option.
-
-Testing
--------
-
-To execute the unit tests run <tt>rake test</tt>.
-
-The unit tests for this plugin use an in-memory sqlite3 database.
-
-Installing the gem
-------------------
-
-* gem sources -a http://gems.github.com (only needed once)
-* sudo gem install dancroak-validates\_email\_format\_of
-
-Credits
--------
-
-Written by Alex Dunae (dunae.ca), 2006-07.
-
-Thanks to Francis Hwang (http://fhwang.net/) at Diversion Media for creating the 1.1 update.
diff --git a/vendor/plugins/validates_email_format_of/README.rdoc b/vendor/plugins/validates_email_format_of/README.rdoc
new file mode 100644 (file)
index 0000000..fd1fa8c
--- /dev/null
@@ -0,0 +1,77 @@
+= validates_email_format_of Gem and Rails Plugin
+
+Validate e-mail addresses against RFC 2822 and RFC 3696.
+
+== Installation
+
+Installing as a gem:
+
+  gem sources -a http://gems.github.com
+  gem install alexdunae-validates_email_format_of
+
+Installing as a Ruby on Rails plugin:
+
+  ./script/plugin install http://github.com/alexdunae/validates_email_format_of.git
+
+
+== Usage
+
+ class Person < ActiveRecord::Base
+   validates_email_format_of :email
+ end
+
+As of version 1.4, it's possible to run e-mail validation tests (including MX 
+checks) without using ActiveRecord or even touching a database.  The 
+<tt>validate_email_format</tt> method will return <tt>nil</tt> on a valid 
+e-mail address or an array of error messages for invalid addresses.
+
+  results = ValidatesEmailFormatOf::validate_email_format(email, options)
+
+  if results.nil?
+    # success!
+  else
+    puts results.join(', ')
+  end
+
+
+=== Options
+
+  :message
+     String. A custom error message (default is: " does not appear to be a valid e-mail address")
+  :on
+     Symbol. Specifies when this validation is active (default is :save, other options :create, :update)
+  :allow_nil
+     Boolean. Allow nil values (default is false)
+  :allow_blank
+     Boolean. Allow blank values (default is false)
+  :check_mx
+     Boolean. Check domain for a valid MX record (default is false)
+  :if
+     Specifies a method, proc or string to call to determine if the validation should occur 
+     (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The method, 
+     proc or string should return or evaluate to a true or false value. 
+  :unless
+     See :if option.
+
+== Testing
+
+To execute the unit tests run <tt>rake test</tt>.
+
+The unit tests for this plugin use an in-memory sqlite3 database.
+
+== Resources
+
+* http://github.com/alexdunae/validates_email_format_of
+* http://code.dunae.ca/validates_email_format_of.html
+
+== Credits
+
+Written by Alex Dunae (dunae.ca), 2006-09.
+
+Thanks to Francis Hwang (http://fhwang.net/) at Diversion Media for creating the 1.1 update.
+
+Thanks to Travis Sinnott for creating the 1.3 update.
+
+Thanks to Denis Ahearn at Riverock Technologies (http://www.riverocktech.com/) for creating the 1.4 update.
+
+Thanks to George Anderson (http://github.com/george) and 'history' (http://github.com/history) for creating the 1.4.1 update.
\ No newline at end of file
diff --git a/vendor/plugins/validates_email_format_of/Rakefile b/vendor/plugins/validates_email_format_of/Rakefile
deleted file mode 100644 (file)
index 0b61743..0000000
+++ /dev/null
@@ -1,12 +0,0 @@
-require 'rake'
-require 'rake/testtask'
-
-test_files_pattern = 'test/*_test.rb'
-Rake::TestTask.new do |t|
-  t.libs << 'lib'
-  t.pattern = test_files_pattern
-  t.verbose = false
-end
-
-desc "Run the test suite"
-task :default => :test
index 41a097dc9e355df78d8cb15d3dafd92332f0d667..bdc8b5794f7ea71f62917ac8e0df6c380730a3b8 100644 (file)
@@ -1 +1 @@
-require File.join(File.dirname(__FILE__), 'rails', 'init')
\ No newline at end of file
+require 'validates_email_format_of'
index 48017e37b12e232e5d63b0d1942fa38bac39ff49..78977fb5b907e812d21852152fd7a57a1ab60a60 100644 (file)
@@ -1,10 +1,52 @@
-# encoding: utf-8
-
 module ValidatesEmailFormatOf
+  require 'resolv'
+  
   LocalPartSpecialChars = Regexp.escape('!#$%&\'*-/=?+-^_`{|}~')
   LocalPartUnquoted = '(([[:alnum:]' + LocalPartSpecialChars + ']+[\.\+]+))*[[:alnum:]' + LocalPartSpecialChars + '+]+'
-  LocalPartQuoted = '\"(([[:alnum:]' + LocalPartSpecialChars + '\.\+]*|(\\\\[\u0001-\uFFFF]))*)\"'
-  Regex = Regexp.new('^((' + LocalPartUnquoted + ')|(' + LocalPartQuoted + ')+)@(((\w+\-+)|(\w+\.))*\w{1,63}\.[a-z]{2,6}$)', Regexp::EXTENDED | Regexp::IGNORECASE)
+  LocalPartQuoted = '\"(([[:alnum:]' + LocalPartSpecialChars + '\.\+]*|(\\\\[\x00-\xFF]))*)\"'
+  Regex = Regexp.new('^((' + LocalPartUnquoted + ')|(' + LocalPartQuoted + ')+)@(((\w+\-+[^_])|(\w+\.[^_]))*([a-z0-9-]{1,63})\.[a-z]{2,6}$)', Regexp::EXTENDED | Regexp::IGNORECASE, 'n')
+
+  def self.validate_email_domain(email)
+    domain = email.match(/\@(.+)/)[1]
+    Resolv::DNS.open do |dns|
+      @mx = dns.getresources(domain, Resolv::DNS::Resource::IN::MX) + dns.getresources(domain, Resolv::DNS::Resource::IN::A)
+    end
+    @mx.size > 0 ? true : false
+  end
+  
+  # Validates whether the specified value is a valid email address.  Returns nil if the value is valid, otherwise returns an array
+  # containing one or more validation error messages.
+  #
+  # Configuration options:
+  # * <tt>message</tt> - A custom error message (default is: "does not appear to be a valid e-mail address")
+  # * <tt>check_mx</tt> - Check for MX records (default is false)
+  # * <tt>mx_message</tt> - A custom error message when an MX record validation fails (default is: "is not routable.")
+  # * <tt>with</tt> The regex to use for validating the format of the email address (default is ValidatesEmailFormatOf::Regex)</tt>
+  def self.validate_email_format(email, options={})
+      default_options = { :message => I18n.t(:invalid_email_address, :scope => [:activerecord, :errors, :messages], :default => 'does not appear to be a valid e-mail address'),
+                          :check_mx => false,
+                          :mx_message => I18n.t(:email_address_not_routable, :scope => [:activerecord, :errors, :messages], :default => 'is not routable'),
+                          :with => ValidatesEmailFormatOf::Regex }
+      options.merge!(default_options) {|key, old, new| old}  # merge the default options into the specified options, retaining all specified options
+            
+      # local part max is 64 chars, domain part max is 255 chars
+      # TODO: should this decode escaped entities before counting?
+      begin
+        domain, local = email.reverse.split('@', 2)
+      rescue
+        return [ options[:message] ]
+      end
+
+      unless email =~ options[:with] and not email =~ /\.\./ and domain.length <= 255 and local.length <= 64
+        return [ options[:message] ]
+      end
+      
+      if options[:check_mx] and !ValidatesEmailFormatOf::validate_email_domain(email)
+        return [ options[:mx_message] ]
+      end
+      
+      return nil    # represents no validation errors
+  end
 end
 
 module ActiveRecord
@@ -17,38 +59,28 @@ module ActiveRecord
       #   end
       #
       # Configuration options:
-      # * <tt>message</tt> - A custom error message (default is: " does not appear to be a valid e-mail address")
+      # * <tt>message</tt> - A custom error message (default is: "does not appear to be a valid e-mail address")
       # * <tt>on</tt> - Specifies when this validation is active (default is :save, other options :create, :update)
       # * <tt>allow_nil</tt> - Allow nil values (default is false)
       # * <tt>allow_blank</tt> - Allow blank values (default is false)
+      # * <tt>check_mx</tt> - Check for MX records (default is false)
+      # * <tt>mx_message</tt> - A custom error message when an MX record validation fails (default is: "is not routable.")
       # * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
       #   occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }).  The
       #   method, proc or string should return or evaluate to a true or false value.
       # * <tt>unless</tt> - See <tt>:if</tt>
       def validates_email_format_of(*attr_names)
-        options = { :message => ' does not appear to be a valid e-mail address', 
-                    :on => :save, 
+        options = { :on => :save, 
                     :allow_nil => false,
-                    :allow_blank => false,
-                    :with => ValidatesEmailFormatOf::Regex }
-
+                    :allow_blank => false }
         options.update(attr_names.pop) if attr_names.last.is_a?(Hash)
 
         validates_each(attr_names, options) do |record, attr_name, value|
           v = value.to_s
-
-          # local part max is 64 chars, domain part max is 255 chars
-          # TODO: should this decode escaped entities before counting?
-          begin
-            domain, local = v.reverse.split('@', 2)
-          rescue
-            record.errors.add(attr_name, options[:message])
-            next
-          end
-
-          unless v =~ options[:with] and not v =~ /\.\./ and domain.length <= 255 and local.length <= 64
-            record.errors.add(attr_name, options[:message])
-          end
+          errors = ValidatesEmailFormatOf::validate_email_format(v, options)
+          errors.each do |error|
+            record.errors.add(attr_name, error)
+          end unless errors.nil?
         end
       end
     end   
diff --git a/vendor/plugins/validates_email_format_of/rails/init.rb b/vendor/plugins/validates_email_format_of/rails/init.rb
deleted file mode 100644 (file)
index bf0e943..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-if defined?(ActiveRecord::Base)
-  require 'validates_email_format_of'
-end
diff --git a/vendor/plugins/validates_email_format_of/rakefile.rb b/vendor/plugins/validates_email_format_of/rakefile.rb
new file mode 100644 (file)
index 0000000..bac695f
--- /dev/null
@@ -0,0 +1,28 @@
+require 'rake'
+require 'rake/testtask'
+require 'rake/rdoctask'
+
+desc 'Default: run unit tests.'
+task :default => [:clean_log, :test]
+
+desc 'Remove the old log file'
+task :clean_log do
+  "rm -f #{File.dirname(__FILE__)}/test/debug.log" if File.exists?(File.dirname(__FILE__) + '/test/debug.log')
+end
+
+desc 'Test the validates_email_format_of plugin.'
+Rake::TestTask.new(:test) do |t|
+  t.libs << 'lib'
+  t.pattern = 'test/**/*_test.rb'
+  t.verbose = true
+end
+
+desc 'Generate documentation for the validates_email_format_of plugin.'
+Rake::RDocTask.new(:rdoc) do |rdoc|
+  rdoc.rdoc_dir = 'rdoc'
+  rdoc.title    = 'validates_email_format_of plugin'
+  rdoc.options << '--line-numbers --inline-source'
+  rdoc.rdoc_files.include('README')
+  rdoc.rdoc_files.include('TODO')
+  rdoc.rdoc_files.include('lib/**/*.rb')
+end
\ No newline at end of file
diff --git a/vendor/plugins/validates_email_format_of/shoulda_macros/validates_email_format_of.rb b/vendor/plugins/validates_email_format_of/shoulda_macros/validates_email_format_of.rb
deleted file mode 100644 (file)
index fb77803..0000000
+++ /dev/null
@@ -1,97 +0,0 @@
-module ValidatesEmailFormatOf
-  module Shoulda
-    def should_validate_email_format_of(field)
-      metaclass = (class << self; self; end)
-      metaclass.send(:define_method,:should_allow_values) do |klass,*values|
-        should_allow_values_for(field, *values)
-      end
-      metaclass.send(:define_method,:should_not_allow_values) do |klass, *values|
-        should_not_allow_values_for(field, values, :message => /valid e-mail/)
-      end
-      should_validate_email_format_of_klass(model_class, field)
-    end
-
-    def should_validate_email_format_of_klass(klass, field)
-      context 'Typical valid email' do
-        should_allow_values(klass,
-          'valid@example.com',
-          'Valid@test.example.com',              
-          'valid+valid123@test.example.com',     
-          'valid_valid123@test.example.com',     
-          'valid-valid+123@test.example.co.uk',  
-          'valid-valid+1.23@test.example.com.au',
-          'valid@example.co.uk',                 
-          'v@example.com',                       
-          'valid@example.ca',                    
-          'valid_@example.com',                  
-          'valid123.456@example.org',            
-          'valid123.456@example.travel',         
-          'valid123.456@example.museum',         
-          'valid@example.mobi',                  
-          'valid@example.info',                  
-          'valid-@example.com')
-      end
-      
-      context 'valid email from RFC 3696, page 6' do
-        should_allow_values(klass,
-          'customer/department=shipping@example.com',
-          '$A12345@example.com',
-          '!def!xyz%abc@example.com',
-          '_somename@example.com')
-      end
-      
-      context 'valid email with apostrophe' do
-        should_allow_values(klass, "test'test@example.com")
-      end
-      
-      context 'valid email from http://www.rfc-editor.org/errata_search.php?rfc=3696' do
-        should_allow_values(klass,
-          '"Abc\@def"@example.com',     
-          '"Fred\ Bloggs"@example.com',
-          '"Joe.\\Blow"@example.com')
-      end
-      
-      context 'Typical invalid email' do
-        should_not_allow_values(klass,
-          'invalid@example-com',
-          'invalid@example.com.',
-          'invalid@example.com_',
-          'invalid@example.com-',
-          'invalid-example.com',
-          'invalid@example.b#r.com',
-          'invalid@example.c',
-          'invali d@example.com',
-          'invalidexample.com',
-          'invalid@example.')
-      end
-      
-      context 'invalid email with period starting local part' do
-        should_not_allow_values(klass,'.invalid@example.com')
-      end
-      
-      context 'invalid email with period ending local part' do
-        should_not_allow_values(klass, 'invalid.@example.com')
-      end
-      
-      context 'invalid email with consecutive periods' do
-        should_not_allow_values(klass, 'invali..d@example.com')
-      end
-      
-      # corrected in http://www.rfc-editor.org/errata_search.php?rfc=3696
-      context 'invalid email from http://tools.ietf.org/html/rfc3696, page 5' do
-        should_not_allow_values(klass,
-          'Fred\ Bloggs_@example.com',
-          'Abc\@def+@example.com',
-          'Joe.\\Blow@example.com')
-      end
-
-      context 'invalid email exceeding length limits' do
-        should_not_allow_values(klass,
-          "#{'a' * 65}@example.com",
-          "test@#{'a'*252}.com")
-      end
-    end
-  end
-end
-
-Test::Unit::TestCase.extend(ValidatesEmailFormatOf::Shoulda)
diff --git a/vendor/plugins/validates_email_format_of/test/database.yml b/vendor/plugins/validates_email_format_of/test/database.yml
new file mode 100644 (file)
index 0000000..2e6ac20
--- /dev/null
@@ -0,0 +1,3 @@
+plugin_test:
+  adapter: sqlite3
+  database: ":memory:"
\ No newline at end of file
diff --git a/vendor/plugins/validates_email_format_of/test/db/email_format_test.sqlite3 b/vendor/plugins/validates_email_format_of/test/db/email_format_test.sqlite3
deleted file mode 100644 (file)
index 0b2dc8c..0000000
Binary files a/vendor/plugins/validates_email_format_of/test/db/email_format_test.sqlite3 and /dev/null differ
diff --git a/vendor/plugins/validates_email_format_of/test/fixtures/people.yml b/vendor/plugins/validates_email_format_of/test/fixtures/people.yml
new file mode 100644 (file)
index 0000000..6a9ec7c
--- /dev/null
@@ -0,0 +1,3 @@
+existing:
+  id: 1
+  email: test@example.com
diff --git a/vendor/plugins/validates_email_format_of/test/fixtures/person.rb b/vendor/plugins/validates_email_format_of/test/fixtures/person.rb
new file mode 100644 (file)
index 0000000..d91c9d0
--- /dev/null
@@ -0,0 +1,12 @@
+class Person < ActiveRecord::Base
+  validates_email_format_of :email, 
+                            :on => :create, 
+                            :message => 'fails with custom message', 
+                            :allow_nil => true
+end
+
+class MxRecord < ActiveRecord::Base
+  validates_email_format_of :email, 
+                            :on => :create, 
+                            :check_mx => true
+end
diff --git a/vendor/plugins/validates_email_format_of/test/schema.rb b/vendor/plugins/validates_email_format_of/test/schema.rb
new file mode 100644 (file)
index 0000000..962bfd5
--- /dev/null
@@ -0,0 +1,10 @@
+ActiveRecord::Schema.define(:version => 0) do
+  create_table :people, :force => true do |t|
+    t.column "email", :string
+  end
+
+  create_table :mx_records, :force => true do |t|
+    t.column "email", :string
+  end
+
+end
\ No newline at end of file
index 0a67debb714b0fbde01f9056a4cd584fb1d9c256..5d200787442d8ec723199364a9339aeb3c33b6c8 100644 (file)
@@ -1,47 +1,40 @@
 $:.unshift(File.dirname(__FILE__) + '/../lib')
+RAILS_ROOT = File.dirname(__FILE__)
 
 require 'rubygems'
+require 'test/unit'
 require 'active_record'
-require 'active_record/base'
+require 'active_record/fixtures'
+require "#{File.dirname(__FILE__)}/../init"
 
-require 'validates_email_format_of'
 
-ActiveRecord::Base.establish_connection(
-  :adapter  => 'sqlite3',
-  :database => ':memory:')
+config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml'))
+ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log")
+ActiveRecord::Base.establish_connection(config[ENV['DB'] || 'plugin_test'])
 
-ActiveRecord::Schema.define(:version => 0) do
-  create_table :users, :force => true do |t|
-    t.column 'email', :string
-  end
-end
+load(File.dirname(__FILE__) + "/schema.rb") if File.exist?(File.dirname(__FILE__) + "/schema.rb")
 
-class Person < ActiveRecord::Base
-  validates_email_format_of :email, :on => :create, :message => 'fails with custom message', :allow_nil => true
+if ActiveSupport.const_defined?(:TestCase)
+  ActiveSupport::TestCase.send(:include, ActiveRecord::TestFixtures)
+  TEST_CASE = ActiveSupport::TestCase
+else
+  TEST_CASE = Test::Unit::TestCase
 end
 
-require 'test/unit'
-require 'shoulda'
-require "#{File.dirname(__FILE__)}/../init"
+TEST_CASE.fixture_path = File.dirname(__FILE__) + "/fixtures/"
+$LOAD_PATH.unshift(TEST_CASE.fixture_path)
 
-class Test::Unit::TestCase #:nodoc:
-  def self.should_allow_values(klass,*good_values)
-    good_values.each do |v|
-      should "allow email to be set to #{v.inspect}" do
-        user = klass.new(:email => v)
-        user.save
-        assert_nil user.errors.on(:email)
-      end
+class TEST_CASE #:nodoc:
+  def create_fixtures(*table_names)
+    if block_given?
+      Fixtures.create_fixtures(TEST_CASE.fixture_path, table_names) { yield }
+    else
+      Fixtures.create_fixtures(TEST_CASE.fixture_path, table_names)
     end
   end
 
-  def self.should_not_allow_values(klass,*bad_values)
-    bad_values.each do |v|
-      should "not allow email to be set to #{v.inspect}" do
-        user = klass.new(:email => v)
-        assert !user.save, "Saved user with email set to \"#{v}\""
-        assert user.errors.on(:email), "There are no errors set on email after being set to \"#{v}\""
-      end
-    end
-  end
+  self.use_transactional_fixtures = false
+  
+  self.use_instantiated_fixtures  = false
 end
+
index 4b048c1b2f7c42131c4765614b447c995206215b..f4c2cc672067d3aee6a66123cf9a63a3a3201a8a 100644 (file)
 require File.dirname(__FILE__) + '/test_helper'
-require File.dirname(__FILE__) + '/../shoulda_macros/validates_email_format_of'
 
-class User < ActiveRecord::Base
-  validates_email_format_of :email,
-    :on        => :create,
-    :message   => 'fails with custom message',
-    :allow_nil => true
-end
+class ValidatesEmailFormatOfTest < TEST_CASE
+  fixtures :people, :peoplemx
+
+  def setup
+    @valid_email = 'valid@example.com'
+    @invalid_email = 'invalid@example.'
+  end
 
-class ValidatesEmailFormatOfTest < Test::Unit::TestCase
-  should_validate_email_format_of_klass(User, :email)
+  def test_without_activerecord
+    assert_nil ValidatesEmailFormatOf::validate_email_format('valid@example.com')
+    err = ValidatesEmailFormatOf::validate_email_format('valid@example-com')
+    assert_equal 1, err.size
+  end
+
+  def test_should_allow_valid_email_addresses
+    ['valid@example.com',
+     'Valid@test.example.com',
+     'valid+valid123@test.example.com',
+     'valid_valid123@test.example.com',
+     'valid-valid+123@test.example.co.uk',
+     'valid-valid+1.23@test.example.com.au',
+     'valid@example.co.uk',
+     'v@example.com',
+     'valid@example.ca',
+     'valid_@example.com',
+     'valid123.456@example.org',
+     'valid123.456@example.travel',
+     'valid123.456@example.museum',
+     'valid@example.mobi',
+     'valid@example.info',
+     'valid-@example.com',
+  # from RFC 3696, page 6
+     'customer/department=shipping@example.com',
+     '$A12345@example.com',
+     '!def!xyz%abc@example.com',
+     '_somename@example.com',
+  # apostrophes
+     "test'test@example.com",
+     ].each do |email|
+      p = create_person(:email => email)
+      save_passes(p, email)
+    end
+  end
 
-  context 'An invalid user on update' do
-    setup do
-      @user = User.new(:email => 'dcroak@thoughtbot.com')
-      assert @user.save
-      assert @user.update_attribute(:email, '..dcroak@thoughtbot.com')
+  def test_should_not_allow_invalid_email_addresses
+    ['invalid@example-com',
+  # period can not start local part
+     '.invalid@example.com',
+  # period can not end local part
+     'invalid.@example.com', 
+  # period can not appear twice consecutively in local part
+     'invali..d@example.com',
+  # should not allow underscores in domain names
+     'invalid@ex_mple.com',
+     'invalid@example.com.',
+     'invalid@example.com_',
+     'invalid@example.com-',
+     'invalid-example.com',
+     'invalid@example.b#r.com',
+     'invalid@example.c',
+     'invali d@example.com',
+     'invalidexample.com',
+     'invalid@example.'].each do |email|
+      p = create_person(:email => email)
+      save_fails(p, email)
     end
+  end
 
-    should 'pass validation' do
-      assert @user.valid?
-      assert @user.save
-      assert_nil @user.errors.on(:email)
+  # from http://www.rfc-editor.org/errata_search.php?rfc=3696
+  def test_should_allow_quoted_characters
+    ['"Abc\@def"@example.com',     
+     '"Fred\ Bloggs"@example.com',
+     '"Joe.\\Blow"@example.com',
+     ].each do |email|
+      p = create_person(:email => email)
+      save_passes(p, email)
     end
   end
 
-  context 'A user with a nil email' do
-    setup { @user = User.new(:email => nil) }
+  # from http://tools.ietf.org/html/rfc3696, page 5
+  # corrected in http://www.rfc-editor.org/errata_search.php?rfc=3696
+  def test_should_not_allow_escaped_characters_without_quotes
+    ['Fred\ Bloggs_@example.com',
+     'Abc\@def+@example.com',
+     'Joe.\\Blow@example.com'
+     ].each do |email|
+      p = create_person(:email => email)
+      save_fails(p, email)
+    end
+  end
 
-    should 'pass validation' do
-      assert @user.valid?
-      assert @user.save
-      assert_nil @user.errors.on(:email)
+  def test_should_check_length_limits
+    ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa@example.com',
+     'test@aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.com'
+     ].each do |email|
+      p = create_person(:email => email)
+      save_fails(p, email)
     end
   end
+
+  def test_should_respect_validate_on_option
+    p = create_person(:email => @valid_email)
+    save_passes(p)
+    
+    # we only asked to validate on :create so this should fail
+    assert p.update_attributes(:email => @invalid_email)
+    assert_equal @invalid_email, p.email
+  end
+  
+  def test_should_allow_custom_error_message
+    p = create_person(:email => @invalid_email)
+    save_fails(p)
+    assert_equal 'fails with custom message', p.errors.on(:email)
+  end
+
+  def test_should_allow_nil
+    p = create_person(:email => nil)
+    save_passes(p)
+  end
+
+  def test_check_mx
+    pmx = MxRecord.new(:email => 'test@dunae.ca')
+    save_passes(pmx)
+
+    pmx = MxRecord.new(:email => 'test@example.com')
+    save_fails(pmx)
+  end
+
+  protected
+    def create_person(params)
+      Person.new(params)
+    end
+
+    def save_passes(p, email = '')
+      assert p.valid?, " validating #{email}"
+      assert p.save
+      assert_nil p.errors.on(:email)
+    end
+    
+    def save_fails(p, email = '')
+      assert !p.valid?, " validating #{email}"
+      assert !p.save
+      assert p.errors.on(:email)
+    end
 end
index 85ffdbb09740c1c2359ce779ee8b5b9eab49f180..2b5206aee6dbc6f611ddb59e37d5e94e0e234a58 100644 (file)
@@ -1,32 +1,18 @@
-Gem::Specification.new do |s|
-  s.name = "validates_email_format_of"
-  s.version = "1.3.0"
-  s.date = "2009-06-08"
-  s.summary = "Validate e-mail addreses against RFC 2822 and RFC 3696."
-  s.email = "dcroak@thoughtbot.com"
-  s.description = "Validate e-mail addreses against RFC 2822 and RFC 3696."
-  s.authors = ["Alex Dunae", "Dan Croak", "Mike Burns"]
-  s.extra_rdoc_files = ["CHANGELOG", 
-    "lib/validates_email_format_of.rb", 
-    "README.markdown"]
-  s.files = ["CHANGELOG", 
-    "init.rb", 
-    "lib/validates_email_format_of.rb", 
-    "MIT-LICENSE", 
-    "rails/init.rb", 
-    "Rakefile", 
-    "README", 
-    "test/database.yml", 
-    "test/fixtures/people.yml", 
-    "test/fixtures/person.rb", 
-    "test/schema.rb", 
-    "test/test_helper.rb", 
-    "test/validates_email_format_of_test.rb", 
-    "Rakefile", 
-    "validates_email_format_of.gemspec"]
+spec = Gem::Specification.new do |s|
+  s.name = 'validates_email_format_of'
+  s.version = '1.4.1'
+  s.summary = 'Validate e-mail addresses against RFC 2822 and RFC 3696.'
+  s.description = s.summary
+  s.extra_rdoc_files = ['README.rdoc', 'CHANGELOG.rdoc', 'MIT-LICENSE']
+  s.test_files = ['test/validates_email_format_of_test.rb','test/test_helper.rb','test/schema.rb','test/fixtures/person.rb', 'test/fixtures/people.yml']
+  s.files = ['init.rb','rakefile.rb', 'lib/validates_email_format_of.rb','rails/init.rb']
+  s.files << s.test_files
+  s.files << s.extra_rdoc_files
+  s.require_path = 'lib'
   s.has_rdoc = true
-  s.homepage = %q{http://code.dunae.ca/validates_email_format_of.html}
-  s.rdoc_options = ["--line-numbers", "--inline-source", "--title", "Validates_email_format_of"]
-  s.require_paths = ["lib"]
+  s.rdoc_options << '--title' <<  'validates_email_format_of'
+  s.author = "Alex Dunae"
+  s.email = "code@dunae.ca"
+  s.homepage = "http://code.dunae.ca/validates_email_format_of.html"
 end