I have the following requirement for valid usernames:
- Only alphanumeric characters and -
- Must not start with a -
I wrote this regex (on Rubular):
/^[^a-zA-Z0-9]|[^a-zA-Z0-9-]+/
Is there a better to test this requirement other than to iterate through all the possible scenarios? I'm doing something like this.
# There much more, but for brevity's sake I'm only including a few
illegal_chars = [ "~", "!", "@", "#", "$"]
illegal_chars.each do |char|
test "username does not accept #{char}" do
user = users(:homer)
user.username = "name#{char}"
refute user.valid?, "Username should not be valid"
end
end
I'll repeat for cases where #{char}
is at the beginning and end of the word.
- Am I testing too much? Is there a better way? Running 70 or 80 tests for something like this seems excessive.
- As an aside, can my regex be expressed better?