简体   繁体   中英

Test unique index Mysql2:Error in RSpec

I have a permalink field in my model which has uniqueness validation in Rails and a unique index in MySQL. When I import data through my API, it happens sometimes, that two requests has the same value for permalink and they try to save at the same time.

In this case, I don't get a uniqueness validation error, I get an error:

ActiveRecord::RecordNotUnique: Mysql2::Error: Duplicate entry 'permalink123' for key 'index_products_on_permalink'

I deal with this case by warpping save in a rescue block, adding a random value to the end of the permalink and try to save again. When the second save also produces an error, it is raised.

But how do test this behaviour in RSpec? I tried to disable the uniqueness validation during the test with

Product.class_eval do
  validates :permalink, uniqueness: false
end

but this does not throw the MySQL error. I also don't think that stubbing the error with expect(product).to receive(:save).and_raise(Mysql2::Error) is the right way, because what happens when the error class and/or error string changes?

Is there a way, where I can produce an Mysql2:Error during my test, that is caused by a unique index error from mysql?

1) Stubbing the save to raise the correct error seems fine to me if the test database isn't throwing the same error :) It's definitely not ideal but at the end of the day it's a test so you just want to ensure you're handling that case the way you expect. A comment of why though is definitely in order!

2) I believe it's up to how you configure the test database. From my experience FactoryGirl doesn't throw unique index errors which is particularly annoying...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM