Rails Transactions

Hi!    I am confused about Rails transactions.... Look at the following code:

CODE BEGINS

Note that this is happening in tests. I mean tests are getting failed.

Tests are special. Because each test itself is wrapped in a transaction by default and because rails does not support nested transactions you cannot test your handling of transactions. If you want to do that you need to turn off transactional fixtures.

Fred

How do I do that?

How do I do that?

set self.use_transactional_fixtures = false (either in your
test_helper.rb which will do it for all tests or just in one of of
your test files)

Fred

Frederick Cheung wrote:

How do I do that?

set self.use_transactional_fixtures = false (either in your test_helper.rb which will do it for all tests or just in one of of your test files)

Fred

OMG,

you do not understand how that just fixed my life. Seriously! I've been bummed out all week cuz my functionals that dealt with transactions were not working properly. I was trying to assert counts after my controllers would throw an exception in a transaction and they never matched up. Even though I searched and read bug filings on a bunch of AR stuff in the Rails Trac server, I *still* couldn't figure out what was going wrong because I didn't remember having this prob on my previous Rails projects.

So to recap and spell it out in case someone else stumbles upon this and doesn't yet get it:

1. Your controllers have something like

def create

# assign your params to person, address, credit card # don't get caught up on the model details as the below # probably isn't the best object graph # And I know, this is straight outta the agile rails book pp. 492-493

Account.transaction do    @credit_card.address=@address    @account.address=@address

   @address.save!    @credit_card.save!    @account.save! end

flash[:message]='Update successful.' render :action=>'show'

rescue Exception => ex

@account.valid? @credit_card.valid? @address.valid? render :action=>'new'

end

2. Your tests have something like

def test_add_credit_card count = CreditCard.count

# do your post, rollback should happen in logs

assert_not_nil assigns(:credit_card) assert_equal count, CreditCard.count

end

This totally made my week. Thank you!! :slight_smile: