Test not null database foreign keys with RSpec

Giovanni Benussi
2 min readSep 29, 2017

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 😄

--

--

Giovanni Benussi
Giovanni Benussi

Written by Giovanni Benussi

Frontend Developer 👨‍💻 Follow me on Twitter 🐦 https://twitter.com/giovannibenussi

No responses yet