[LRUG] Handling opening and closing of transactions manually in ActiveRecord

Tim Cowlishaw tim at timcowlishaw.co.uk
Fri Oct 8 03:32:09 PDT 2010


Hey all,

I stumbled across Xavier Shay's article on setting up RSpec to use
transactional before(:all) blocks with datamapper the other day
(http://rhnh.net/2010/10/06/transactional-before-all-with-rspec-and-datamapper),
which is convenient as it's something I've been meaning to do for ages
on one of our codebases that has a rather large test suite with lots
of setup in before(:each) blocks. Therefore, I thought I'd spend a bit
of time trying to get his solution working with ActiveRecord, rather
than Datamapper. However, because ActiveRecord's transaction interface
requires you to pass a block to the transaction method, containing the
work to be done within the transaction, rather than offering
transaction.begin and transaction.rollback methods a la datamapper,
this is a little trickier than expected. There is
ActiveRecord::Base.connection.begin_db_transaction, and
ActiveRecord::Base.rollback_db_transaction, but these don't handle
emulating nesting transactions with savepoints as
ActiveRecord::Base.transaction does, meaning I'd have to reimplement
that seperately - not an insurmountable task, but a sufficiently
complex bit of work to make me nervous. Therefore, has anyone run into
a similar need (to make before(:all) blocks transactional in rspec)
before? if so, how did you manage it?

Cheers,

Tim



More information about the Chat mailing list