A Journey On Rails

Testing Transactions

Posted in Uncategorized by Vikram Venkatesan on January 8, 2010

If you ever ran into a situation where you were not able to test the transaction logic in your code, the reason could have been that, rails runs each test case as a transaction itself and hence you don’t see the actual effect of rollback happening for your transaction. This happens when you are using transactional_fixtures that create fixture records only once while running the test suite life time by running the test cases as transactions, thereby undoing any DML modifications, leaving the fixtures intact. The default test_helper.rb generated by rails will have the following lines of code

# The only drawback to using transactional fixtures is when you actually
# need to test transactions.  Since your test is bracketed by a transaction,
# any transactions started in your code will be automatically rolled back.
self.use_transactional_fixtures = true

You can switch off trasactional fixtures for all tests by calling self.use_transactional_fixtures = false in your test_helper or in your test class. But, that will result in way too slow tests. How about disabling it only for the specific test case alone? From what i know, there isn’t a way to do so.

What you can rather do is, write a separate test class for such transactional tests setting self.use_transactional_fixtures = false. Things will work fine as you expected. One word of caution though! Now that you have disabled transactions, it’s your duty to clean up any data created by the test case(s), so that the new test class can co-exist with other tests using transactional fixtures. You can either do this manually at the end of the test method(s) or override the teardown method and add the cleanup code to it.

def teardown
 # Your code for undoing the data changes goes here....
end

Happy testing!!!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: