There are two common ways to run transactional tests.  The first common way 
is using transactions around each spec and loading all data inside each 
spec:

  # pseudocode
  around do
    DB.transaction(:rollback=>:always, :auto_savepoint=>true){super}
  end
  before do
    add_data_for_tests
  end

The problem with this approach is that for every spec, you need to add the 
same data for the tests, which can be a significantly slowdown.

The second common way is to load the data before the tests, use 
transactions for each spec, then clean up the added data after the spec:

  # pseudocode
  before_all do
    add_data_for_tests
  end
  around do
    DB.transaction(:rollback=>:always, :auto_savepoint=>true){super}
  end
  after_all do
    remove_data_added_in_before_all
  end

The problem with this is that you need to manually keep the after(:all) 
code in sync with the before(:all) code.

If you are using minitest for your testing, I've just released a 
minitest-hooks library that supports an around_all capability.  Using 
around_all, you get the best of both worlds by wrapping all specs in a 
describe block in a transaction, and wrapping each spec in a savepoint 
inside that transaction.  This allows for the following type of code:

  # pseudocode
  around_all do
    DB.transaction(:rollback=>:always){super}
  end
  around do
    DB.transaction(:rollback=>:always, :savepoint=>true, 
:auto_savepoint=>true){super}
  end
  before_all do
    add_data_for_tests
  end

Using this, you only need to load the data for the test suite once (in 
before_all), each spec uses the same data, changes are rolled back after 
each spec, and after all specs execute, the data added in before_all is 
rolled back, leaving your test database in pristine state.

If you are interested, check it 
out: https://github.com/jeremyevans/minitest-hooks

Note that if you are using RSpec, there 
is https://github.com/seanwalbran/rspec_around_all, but that uses fibers 
since RSpec doesn't natively support around_all.  With minitest, it's 
simple to hook into the default behavior and add support for around_all.

If you want an example of minitest-hooks usage in a real application using 
Sequel, see: https://github.com/jeremyevans/giftsmas/tree/master/spec

Thanks,
Jeremy

-- 
You received this message because you are subscribed to the Google Groups 
"sequel-talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/sequel-talk.
For more options, visit https://groups.google.com/d/optout.

Reply via email to