How to test that a certain function uses a transaction in Rails and rspec 2 How to test that a certain function uses a transaction in Rails and rspec 2 ruby ruby

How to test that a certain function uses a transaction in Rails and rspec 2


You should look at the problem from a different perspective. Testing whether a function uses a transaction is useless from a behavioral viewpoint. It does not give you any information on whether the function BEHAVES as expected.

What you should test is the behavior, i.e. expected outcome is correct. For clarity, lets say you execute operation A and operation B within the function (executed within one transaction). Operation A credits a user 100 USD in your app. Operation B debits the users credit card with 100 USD.

You should now provide invalid input information for the test, so that debiting the users credit card fails. Wrap the whole function call in an expect { ... }.not_to change(User, :balance).

This way, you test the expected BEHAVIOR - if credit card debit fails, do not credit the user with the amount. Also, if you just refactor your code (e.g. you stop using transactions and rollback things manually), then the result of your test case should not be affected.

That being said, you should still test both operations in isolation as @luacassus mentioned. Also, it is exactly right that your test case should fail in case you made an "incompatible" change (i.e. you change the behavior) to the sourcecode as @rb512 mentioned.


A big gotcha needs to be mentioned: When testing transaction, you need to turn off transactional_fixtures. This is because the test framework (e.g Rspec) wraps the test case in transaction block. The after_commit is never called because nothing is really committed. Expecting rollback inside transaction doesn't work either even if you use :requires_new => true. Instead, transaction gets rolled back after the test runs. Ref http://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html nested transactions.


Generally you should use "pure" rspec test to test chunks of application (classes and methods) in the isolation. For example if you have the following code:

class Model   def method   Model.transaction do     first_operation     second_operation   endend

you should test first_operation and second_operation in separate test scenarios, ideally without hitting the database. Later you can write a test for Model#method and mock those two methods.

At the next step you can write a high level integration test with https://www.relishapp.com/rspec/rspec-rails/docs/request-specs/request-spec and check how this code will affect the database in different conditions, for instance when second_method will fail.

In my opinion this is the most pragmatic approach to test a code which produces complex database queries.