Raising ActiveRecord::Rollback
I had a bit of code that I was running in a transaction block. Like so:
ActiveRecord::Base.transaction do @rating = Rating.new(rater: @user, rateable: @movie, score: params[:score]) if !@rating.save Rails.logger.error("Error saving rating") raise ActiveRecord::Rollback end end
I kept trying to test this by doing:
expect { post :create etc }.to raise_error ActiveRecord::Rollback
Total failure. Couldn’t figure out why for a while. Here’s the reason: raising ActiveRecord::Rollback just triggers a rollback of the transaction and does so silently. What I should’ve done is raise a different type of error (TBD) and that will still trigger a rollback of the transaction but the error will actually be raised and we can return an appropriate page to the user.
More info on StackOverflow.