[rspec-users] How to modify database inside a transaction in before(:all)?

David Chelimsky dchelimsky at gmail.com
Mon Apr 23 23:04:03 UTC 2012

On Mon, Apr 23, 2012 at 5:39 PM, Rodrigo Rosenfeld Rosas
<rr.rosas at gmail.com> wrote:
> I have a set of examples that should run with a specific set of records in
> the database.
> Since setting those records is an expensive operation I'd like to perform it
> just once per context.
> For example:
> context 'sample tree' do
>     before(:all) { create_tree_records }
>     example ...
> end
> The problem with this is that while before(:each) and the examples will run
> in a transaction that will be rolled back at the end of each example, that
> won't happen to the records created/modified by the before(:all) block.
> It seems my database vendor (PostgreSQL) supports nested transactions
> (savepoints):
> http://www.postgresql.org/about/
> I should also notice that I'm using Sequel and it seems that transactions
> are reentrant in Sequel:
> http://cheat.errtheblog.com/s/sequel/
> Database#transaction is re-entrant:
>   DB.transaction do # BEGIN issued only here
>     DB.transaction
>       dataset << {:first_name => 'Inigo', :last_name => 'Montoya'}
>     end
> end # COMMIT issued only here
> So, this logic wouldn't work for me. I need a save point in a before(:all),
> so that I'd restore it on a before(:each).
> Is there any recommendation to make this work in my specs?

Nothing built into RSpec now, but you could disable the Rails
transaction management and use DatabaseCleaner on your own.

This is currently being discussed in
https://github.com/rspec/rspec-rails/issues/496 as well. Feel free to
join that convo.


> Thanks in advance,
> Rodrigo.

More information about the rspec-users mailing list