Image for post
Image for post

Test not null database foreign keys with RSpec

Sometimes you would like to let explicit in a test that, beyond ActiveRecord validations, a record can’t be saved if a related model doesn’t exists.

Let’s suppose that you have created a reference from a post to a user this way:

Besides that reference, you could still save a post without an user directly in your database or in your code:

However, you need to be sure that this doesn’t happen so you can avoid to be afraid of edge cases in your code.

To validate that a model can’t be saved in databaset without validation you could use the following:

Here we are testing that when we try to save a record without validation, a ActiveRecord::NotNullViolation exception should be raised.

To make this test pass you need to enforce a null constraint in your database either creating the user_id column as not null in first instance or by changing the column to not allow null user_id values.

This way, you can be sure that there are no NULL records in your database, and, if someday someone tries to remove that constraint, at least can be aware that someone doesn’t want that to happen and could investigate further the reasons for that.

If you find this article useful, you can follow me on Twitter where I constantly post tips, articles, and random stuff 😅

A couple of claps will be very appreciated too 😄

Written by

Frontend Developer 👨‍💻 Follow me on Twitter 🐦

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store