0

This is an absolute beginners question, it's probably pretty obvious but I couldn't find the answer yet.

I'm trying to validate an email address in Ruby on Rails using minitest.

test "should have format of email address" do
    user = User.create(name: "Dummy", last_name: "Dummy", email: "example.com")
    assert_match(/\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, user.email)
    assert_equal ["is invalid"], user.errors[:email]
end

The problem occurs in the last line assert_equal ["is invalid"], user.errors[:email].

The email address example.com isn't matched by the regex on purpose since I want to check the error message "is invalid" against the one of the failed test but I can't figure out how to pass it into assert_equal:

Error Message:

Expected /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i to match "example.com".

Should be:

'is invalid.'

Maybe I am wrong, but I my understanding was that error messages of the object could be found in object.errors[:symbol].

loxosceles
  • 347
  • 5
  • 21

1 Answers1

1

The problem actually occurs on the second line:

assert_match(/\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, user.email)

The email you are using is "example.com", and it fails the REGEXP match. Try using something like "dummy@example.com" instead.

blowmage
  • 8,854
  • 2
  • 35
  • 40
  • I actually want to check if the error message is correct (should be: `is invalid`. That's why I purposely have this test failing (by passing it an incorrect email address). I was pretty sure that the error message would appear in `user.errors[:email]` but that doesn't seem to be true. That's why I compare the two error messages in the last line. – loxosceles Oct 13 '14 at 21:17
  • 1
    Then you should split those two asserts into two separate test methods. The assert_match is failing and the assert_equal is not ever run. – blowmage Oct 21 '14 at 19:20