Hi All,
I think that I might have found a bug in the validates_format_of
method. Below is my code and the test case that threw an error.
Please let me know if there is a bug in my code that I just didn’t
catch.
Here is the code for my User model. As you can see, it has one
attribute called name. I wanted to make sure that the names had to be
at least 6 characters long and consisted only of letters, numbers,
dots (.), underscores (_) and at symbols (@).
class User < ActiveRecord::Base
validates_presence_of :name
validates_uniqueness_of :name
validates_format_of :name, :with => /\A[.\w@]{6,}\z/
end
Here is the code for a unit test that I wrote. This unit test tries
to create a fairly comprehensive set of invalid names by creating
several tests for each ASCII character that shouldn’t be part of a
valid name such as ~ or `. None of the bad names that are created
should be valid.
def test_invalid_name
bad_characters = []
for i in 0…255
bad_characters << i.chr unless i.chr =~ /[.\w@]/
end
bad_names = []
bad_characters.each do |c|
bad_names << (c + "abcdef")
bad_names << ("abcdef" + c)
bad_names << ("abc" + c + "def")
bad_names << (c + "abc" + c + "def" + c)
end
bad_names.each do |name|
user = User.new(:name => name, :password =>
“password”, :password_confirmation => “password”)
assert !user.valid?
assert user.errors.invalid?(:name), “Name:” + name
end
end
When I ran this test, it failed for bad characters that are extended
ASCII characters (i.e., characters that have an ASCII value between
128 and 255).
For example, user.valid? had a value of true when the name was
Çabcdef The ASCII value of Ç is 128. User.valid? should have had a
value of false because the name doesn’t match the regex that I used in
the validates_format_of method call. In fact, the result of user.name
=~ /\A[.\w@]{6,}\z/ is false.
Can anyone tell me if there is a bug in my code or not? Any help
would be appreciated!