Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

unit testing - ActiveRecord Rollback does not work in Rails test

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...