1

Throwing ActiveRecord::Rollback works, but not in tests.

I've had this problem before, am now having it again, and for some reason can't find any record of someone else having this problem.

I'm this is because tests do a rollback each time a test runs, and most databases don't support nested rolllbacks. However, I can't be the only person with test cases that involve a transaction rollback, so perhaps I am doing something wrong.

The following test case fails (uses shoulda library, though the same test fails with basic Test::Unit):

require 'test_helper'

class RollbackTest < ActiveSupport::TestCase
  context "create a record and throw rollback" do
    setup do
      User.transaction do
        User.create!
        raise ActiveRecord::Rollback
      end
    end

    should_not_change("count of users") { User.count }
  end
end

however on the console:

?> User.transaction do
?>         User.create!
>>         raise ActiveRecord::Rollback
>>       end
=> nil
>> User.count
=> 4
>> User.transaction do
?>         User.create!
>>         raise ActiveRecord::Rollback
>>       end
=> nil
>> User.count
=> 4
Alex Neth
  • 3,326
  • 2
  • 26
  • 36

2 Answers2

8

You should turn off transactions in your test case:

class RollbackTest < ActiveSupport::TestCase
  self.use_transactional_fixtures = false

[edit: as per @Conrad's comment it should be transactionAL]

smathy
  • 26,283
  • 5
  • 48
  • 68
Andrew Vit
  • 18,961
  • 6
  • 77
  • 84
  • Thanks. I'm a little surprised that didn't break any of my other tests. I use factory_girl instead of fixtures. – Alex Neth Sep 23 '10 at 02:30
2

Actually the method to call is as follows:

class RollbackTest < ActiveSupport::TestCase
  self.use_transactional_fixtures = false

not self.use_transaction_fixtures (note the missing 'al')

Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
Conrad
  • 21
  • 1
  • 5
    Hey there. Welcome to StackOverflow - thanks for your correction. When there's an existing answer which is essentially correct, but just contains a typo or something, **especially** when it's already marked as the answer - it's better to just edit the answer than to add a new answer. – smathy Apr 28 '11 at 17:44