Skip to content

Commit a1f523b

Browse files
committed
Document transactions in the testing guide
1 parent 5a828e9 commit a1f523b

File tree

1 file changed

+42
-8
lines changed

1 file changed

+42
-8
lines changed

guides/source/testing.md

Lines changed: 42 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -400,6 +400,44 @@ Each of these classes include `Minitest::Assertions`, allowing us to use all of
400400
NOTE: For more information on `Minitest`, refer to [its
401401
documentation](http://docs.seattlerb.org/minitest).
402402

403+
### Transactions
404+
405+
By default, Rails automatically wraps tests in a database transaction that is
406+
rolled back after they finish. This makes tests independent of each other and
407+
changes to the database are only visible within a single test.
408+
409+
```ruby
410+
class MyTest < ActiveSupport::TestCase
411+
test "newly created users are active by default" do
412+
# Since the test is implicitly wrapped in a database transaction, the user
413+
# created here won't be seen by other tests.
414+
assert User.create.active?
415+
end
416+
end
417+
```
418+
419+
The method `ActiveRecord::Base.current_transaction` still acts as intended,
420+
though:
421+
422+
```ruby
423+
class MyTest < ActiveSupport::TestCase
424+
test "current_transaction" do
425+
# The implicit transaction around tests does not interfere with the
426+
# application-level semantics of current_transaction.
427+
assert User.current_transaction.blank?
428+
end
429+
end
430+
```
431+
432+
Individual test cases can opt-out:
433+
434+
```ruby
435+
class MyTest < ActiveSupport::TestCase
436+
# No implicit database transaction wraps the tests in this test case.
437+
self.use_transactional_tests = false
438+
end
439+
```
440+
403441
### The Rails Test Runner
404442

405443
We can run all of our tests at once by using the `bin/rails test` command.
@@ -598,15 +636,11 @@ $ PARALLEL_WORKERS=15 bin/rails test
598636

599637
### Testing Parallel Transactions
600638

601-
Rails automatically wraps any test case in a database transaction that is rolled
602-
back after the test completes. This makes test cases independent of each other
603-
and changes to the database are only visible within a single test.
604-
605-
When you want to test code that runs parallel transactions in threads,
606-
transactions can block each other because they are already nested under the test
607-
transaction.
639+
When you want to test code that runs parallel database transactions in threads,
640+
those can block each other because they are already nested under the implicit
641+
test transaction.
608642

609-
You can disable transactions in a test case class by setting
643+
To workaround this, you can disable transactions in a test case class by setting
610644
`self.use_transactional_tests = false`:
611645

612646
```ruby

0 commit comments

Comments
 (0)