Forum: Ruby on Rails Problems with UnitTest on a class with a transaction in it.

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Guardia A. (Guest)
on 2007-02-10 10:32
(Received via mailing list)
Hi, i've problems  trying to test a simple class with a transaction in
it.

The class is a simple "account" class like this:

class Account < ActiveRecord::Base
   def increase(value)
     self.value = self.value + value
     self.save
   end
   def decrease(value)
     raise ArgumentError,"no founds" if value > self.value
     self.value = self.value - value
     self.save
   end
end

and the bank class is this:

class Bank
   def transfer(account_1, account_2,value)
     begin
       Account.transaction do
         account_1.increase(value)
         account_2.decrease(value)
       end
     rescue => e
       raise e
     end
   end
end

Using the class within the rails application, everything runs
smoothly. Trying to transfer an amount that exceed the remaining
founds, the class raises an exception and the transaction rollbacks
correctly. The class is used inside a bank controller, etc...

But when i try to UnitTest the same class with a test like this:

   def test_transfer_failed
     bank = Bank.new
     inner = accounts(:one)
     outer = accounts(:two)
     inner.update_attribute(:value,200)
     inner.update_attribute(:value,300)

     assert_raise(ArgumentError) do
       bank.transfer(inner,outer,240)
     end

     assert_equal 200,inner.value
     assert_equal 300,outer.value
   end

the test fails, like if the transfer complete and the transaction
doesn't rollbacks.

Anyone can explain me why the test fails? Why the class doesn't
rollbacks while inside the test?

Any help appreciated,

thanks.
Jeremy K. (Guest)
on 2007-02-10 11:07
(Received via mailing list)
On 2/10/07, Guardia A. <removed_email_address@domain.invalid> wrote:
> Hi, i've problems  trying to test a simple class with a transaction in
> it.

Set self.transactional_fixtures = false at the beginning of your test
class.

Tests are wrapped in transactions by default so any changes the test
makes to the database may be easily rolled back.

jeremy
alessino (Guest)
on 2007-02-10 14:13
(Received via mailing list)
On Feb 10, 10:06 am, "Jeremy K." <removed_email_address@domain.invalid> wrote:

> Set self.transactional_fixtures = false at the beginning of your test class.
>
> Tests are wrapped in transactions by default so any changes the test
> makes to the database may be easily rolled back.

 Thank you for the  answer, but i've already turned off transactional
fixtures in this test.
This topic is locked and can not be replied to.