⬆️ ⬇️

ActiveRecord and mystically falling specs

Today, while developing a project, one Ruby on Rails project has discovered a strange feature: two specs are falling. No one in the project does not fall, but I - fall. The code, gems, system and software are the same, only my specs are falling, and the other project participants do not.



In order to get into the depths of the code. The reason that the spec is not passed is incorrect handling of the index uniqueness violation in the database. Stop, because the cake and checks this situation, how so. I’m going to the error-handling block, yes, it is, an ActiveRecord :: RecordNotUnique exception is caught and correctly processed, which ActiveRecord throws out when trying to insert a non-unique value into a table with a unique index. Let's see how the generation of this exception is implemented in ActiveRecord for PostgreSQL:







As you can see, the generation of one or another exception occurs depending on the error message returned by the base. And then everything falls into place: in my PostgreSQL settings (file /etc/postgresql/8.4/main/postgresql.conf) the following option is set:

')

lc_messages = 'ru_RU.UTF-8' # locale for system error message



and instead of the expected “duplicate key value violates unique constraint”, the database returns localized: “the duplicate key value violates the uniqueness condition”, which leads to the generation of a completely different exception, and therefore, destroys the entire code.



So who is to blame and what to do? In my case, it suffices to change the localization of error messages in the PosgreSQL config. But in general, in the rails code, if possible, it is better to add a validation for uniqueness to the model (validate: field,: uniqueness => true) and not to form the application logic based on the type of exceptions from the database.



UPD. This problem is relevant only for the PosgtreSQL adapter; in MySQL, processing is based on the error code, and not on the text description:

Source: https://habr.com/ru/post/137803/



All Articles