ActiveRecord 回滚在 Rails 测试中不起作用

发布于 2024-09-24 06:12:04 字数 927 浏览 4 评论 0原文

抛出 ActiveRecord::Rollback 有效,但在测试中无效。

我以前遇到过这个问题,现在又遇到了这个问题,并且由于某种原因找不到其他人遇到此问题的任何记录。

我这是因为测试每次运行时都会进行回滚,并且大多数数据库不支持嵌套回滚。但是,我不可能是唯一一个拥有涉及事务回滚的测试用例的人,所以也许我做错了什么。

以下测试用例失败(使用 shoulda 库,尽管相同的测试使用基本 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

但是在控制台上:

?> 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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

漆黑的白昼 2024-10-01 06:12:04

您应该关闭测试用例中的事务:

class RollbackTest < ActiveSupport::TestCase
  self.use_transactional_fixtures = false

[编辑:根据 @Conrad 的评论,它应该是 transactionAL]

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]

忘羡 2024-10-01 06:12:04

实际上调用的方法如下:

class RollbackTest < ActiveSupport::TestCase
  self.use_transactional_fixtures = false

不是self.use_transaction_fixtures(注意缺少'al')

Actually the method to call is as follows:

class RollbackTest < ActiveSupport::TestCase
  self.use_transactional_fixtures = false

not self.use_transaction_fixtures (note the missing 'al')

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文