Today I Learned

A Hashrocket project

Transaction within a transaction

When using transactional fixtures in rspec, you’re likely to always be in a transaction. When that’s the case, transactions in you’re code don’t necessarily behave as you’d expect.

def update
  ActiveRecord::Base.transaction do
    Thing.find(params[:id]).update_attributes(color: 'red')
    raise ActiveRecord::Rollback
  end
end

In this case the transaction won’t rollback the changes to Thing, and if you’re testing that rollback in rspec, you’ll be very confused.

While not the perfect solution, it’s possible to force this transaction to behave how you’d like it to with the requires_new: true named argument which makes the transaction a ‘sub-transaction’.

  ActiveRecord::Base.transaction(requires_new: true) do
  end

documentation

Looking for help? Hashrocket has been an industry leader in Ruby on Rails since 2008. Rails is a core skill for each developer at Hashrocket, and we'd love to take a look at your project. Contact us and find out how we can help you.