Rails transaction not rolling back
This was just a testing issue with rspec because you're already executing in a transaction in the test. It's the same nested transaction issue discussed here. In order to get the test to work you need to add…
requires_new: true
to the transaction call.
This fixed the test.
def process_photos(photos)
ActiveRecord::Base.transaction(requires_new: true) do
begin
photos.each do |photo|
Photo.create!(creator_user: @user, buyer: @buyer, url: photo['url'])
end
rescue
raise ActiveRecord::Rollback
end
end
end
Important: Rollbacks will only work if your database engine supports them! For example MySQL with MyISAM doesn't support transactions, while MySQL with Inno DB does support them.