ActiveRecord::NotNullViolation when testing with RSpec

Zain Butt
Sendoso Engineering
Aug 2, 2019

--

When testing Rails Model and you encounter a ActiveRecord::NotNullViolation, this means you need to provide some default value for an attribute. Normally Mysql wont bug you to provide it, but in newer versions it does require it.

In my case it was due to created_at field without a default value.

ActiveRecord::NotNullViolation:Mysql2::Error: Field 'created_at' doesn't have a default value

This happens when Mysql turns on its strict mode by default and requires you to provide a default value for the attribute. If you don’t want to provide a value then you can just simply turn off strict mode by adding this to database.yml file:

test:
host: ...
username: ...
strict: false

Now run your specs and they will pass without throwing this error.

Happy Coding!!

--

--