Created
December 7, 2012 22:58
-
-
Save jtrim/4237237 to your computer and use it in GitHub Desktop.
Thorougly testing regex validations
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
| # /app/models/foo.rb | |
| class Foo < ActiveRecord::Base | |
| validates_format_of :zip, with: /^[0-9]{5}$/, message: 'must be a valid 5-digit ZIP' | |
| end | |
| # /spec/models/foo_spec.rb | |
| require 'spec_helper' | |
| describe Foo do | |
| describe 'validations' do | |
| it { should_not allow_value("12345\n12345").for(:zip) } | |
| end | |
| end | |
| # What do you think happens??? | |
| # output: `$ rspec spec/models/foo_spec.rb` | |
| F | |
| Expected errors when zip is set to "12345\n12345", got no errors | |
| # Why? | |
| # /app/models/foo.rb corrected | |
| class Foo < ActiveRecord::Base | |
| validates_format_of :zip, with: /\A[0-9]{5}\z/, message: 'must be a valid 5-digit ZIP' | |
| end | |
| # Use `\A` (beginning of string) and `\z` (end of string) where possible in stead of `^` and `$`. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment