0

So in Rails I've written these validations for an email :

validates :email, presence: true, uniqueness: true
validates_format_of :email, :with => /\A[^@\s]+@([^@\s]+\.)+[^@\s]+\z/

When I try to submit something with a wrong email this works because it sends me an error, but when I try to test it like this :

test "should not save if email is not valid" do
    slogan = Slogan.create(firstname: 'tristan', lastname: 'vermeesch', email: 'titivermeeschgmail.com', slogan: 'Test')
    assert slogan.valid?, "Tried to save with an email that is not valid"
  end

The test fails, can someone please help?

2
  • What are you trying to test in the 2nd scenario? The error message? Commented Jun 6, 2019 at 10:43
  • I'm testing that an invalid email shouldn't be saved @AsimHashmi Commented Jun 6, 2019 at 10:45

1 Answer 1

2

If you are trying to test that your model should not be saved and it should have errors when wrong email is given, you can use the valid? method and error? property. Your test would be like this:

test "should not save if email is not valid" do
    slogan = Slogan.create(firstname: 'tristan', lastname: 'vermeesch', email: 'titivermeeschgmail.com', slogan: 'Test')
    assert_not_nil slogan.errors[:email]
  end
Sign up to request clarification or add additional context in comments.

1 Comment

This looks like you are testing the same thing twice...maybe remove assert_equal slogan.valid?, false?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.