Pierre P.
Pierre P.

Reputation: 1065

Unexpected regex behavior in rails

I have the following regex expression to validate emails VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

I have also the following test function

test "valid signup information" do
    get signup_path
    assert_difference 'User.count', 1 do
      post users_path, params: { user: { first_name: "John",
                                         last_name: "Doe",
                                         email: "[email protected]",
                                         password: "foobar123",
                                         password_confirmation: "foobar123" } }
    end
    follow_redirect!
    assert_template 'users/show'
    assert is_logged_in?
end

Yet, the test fails only when the email is set to [email protected] Every single other mail of the same format works. I can't see why. Moreover, when I try to manually sign up, the [email protected] address works perfectly fine.

Here's the log message when testing with [email protected]

Running via Spring preloader in process 5405
Started with run options --seed 28654

 FAIL["test_valid_signup_information", UsersSignupTest, 1.127243652001198]
 test_valid_signup_information#UsersSignupTest (1.13s)
        "User.count" didn't change by 1.
        Expected: 2
          Actual: 1
        test/integration/users_signup_test.rb:19:in `block in <class:UsersSignupTest>'

  20/20: [=============================================================================================================================================================] 100% Time: 00:00:01, Time: 00:00:01

Finished in 1.14680s

Thanks,

Upvotes: 0

Views: 73

Answers (2)

Danil Speransky
Danil Speransky

Reputation: 30453

The regex is fine, you can check it by doing in terminal:

> '[email protected]' =~ /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
=> 0

The failure only says the number of users didn't change. So it could be anything really. After running your tests open console with rails c test and try to create the failed user manually. You will see why it doesn't get created in your test environment.

Upvotes: 1

linden2015
linden2015

Reputation: 887

Your regex pattern isn't so great.

  • It matches: [email protected]
  • It doesn't match: a_b@d_e.com
  • If you put the - at the end or beginning of the character class, then you don't need to escape it. [\w+.-]
  • For readability: ^ and $ are far more commonly used.

Email pattern matching is a hard problem. I suggest googling it instead of coming up with your own pattern. Or make the pattern only catch basic errors and emailing the address will tell you if it's valid or not.

Also, your email pattern should have it's own test, to isolate it's proper working. Then when you test a signup method you're only testing the code belonging to that.

Upvotes: 0

Related Questions