An easier way to test a valid username 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?
Your regex looks wrong, see my link below.

If your functional requirement is that usernames match a certain regex, then your tests should reflect that. It is wrong to test a bunch of edge cases that a generic regex catches.

See this. All you need in your test is to do:

username_regex = /^[a-z0-9][a-z0-9-]*$/i
passing_usernames = ['passing','pAsSing-PASS-'.....]
failing_usernames = ['-failing','failing#'....]
passing_usernames.each { |username| assert_match username_regex, username}
failing_usernames.each { |username| assert_no_match username_regex, username }


If you're getting your username from somewhere else then just plug that in the same way.