Rails not rolling back transaction after failed save()

后端 未结 2 1602
刺人心
刺人心 2021-01-13 19:18

I have this domain model: A user has group of items, and the state of the items can fail a validation.

Validation works fine, and I even see exceptions get called wh

相关标签:
2条回答
  • 2021-01-13 19:33

    It sounds like you're hitting a nested transaction problem in your tests.

    I don't believe the Ruby driver for Postgres handles nested transactions, so you only get the scope of the outer transaction. If you have transactional fixtures enabled, there's an outer transaction wrapping your test execution. This means if your controller under test creates a second, inner transaction, and attempts to roll it back - you may not get the right behavior.

    You can confirm the transaction interference by turning off the transactions in rspec:

    RSpec.configure do |config|
      config.use_transactional_fixtures = false
    end
    
    0 讨论(0)
  • 2021-01-13 19:50

    Adding an item to the collection saves it immediately (unless the user is unsaved). The call to save creates its own transaction and that is what is rolled back, not the transaction in which the item is saved

    You could force everything into the same transaction by creating one explicitly.

    begin
      User.transaction do
        @user.items << item
        @user.save!
        render :json => {}, :status => :ok
      end
    rescue ActiveRecord::RecordInvalid
      render :json => {:status => :error, :errors => item.errors}, :status => :bad_request
    end
    
    0 讨论(0)
提交回复
热议问题