Test ActiveRecord Validations

Victor Hazbun
InstructorVictor Hazbun
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 3 years ago

Learn how to test ActiveRecord validations using RSpec.

In this lesson we'll write a test that expects the name attribute to be present on the User model instance. We'll see that at first this test fails because we need to add this validation on the model.

Instructor: [0:00] Let's test the username presence validation. When the name attribute is blank, it should have errors on the name attribute. We will need to set up a user instance. The name attribute must be blank.

[0:15] Next, we trigger the validation on the user instance by calling the valid method. This will also set the errors on the name attribute. We expect the name attribute errors to be "Can't be blank."

[0:32] Now let's run the text to see them fail. The test failed because we have not implemented the validation on the user model.

[0:40] To validate name presence, we call validate followed by the attribute name with the option presence true. If we run the test again, they pass because we implemented the presence validation on the name attribute.

egghead
egghead
~ 18 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today