Search code examples
tddintegration-testingdatabase-testing

Database integration tests


When you are doing integration tests with either just your data access layer or the majority of the application stack. What is the best way prevent multiple tests from clashing with each other if they are run on the same database?


Solution

  • Transactions.

    What the ruby on rails unit test framework does is this:

    Load all fixture data.
    
    For each test:
    
      BEGIN TRANSACTION
    
        # Yield control to user code
    
      ROLLBACK TRANSACTION
    
    End for each
    

    This means that

    1. Any changes your test makes to the database won't affect other threads while it's in-progress
    2. The next test's data isn't polluted by prior tests
    3. This is about a zillion times faster than manually reloading data for each test.

    I for one think this is pretty cool