Skip to content

Instantly share code, notes, and snippets.

@jtrim
Created December 7, 2012 22:58
Show Gist options
  • Select an option

  • Save jtrim/4237237 to your computer and use it in GitHub Desktop.

Select an option

Save jtrim/4237237 to your computer and use it in GitHub Desktop.
Thorougly testing regex validations
# /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