ActiveRecord::NotNullViolation when testing with RSpec

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!!

--

--

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