ActiveRecord 回滚在 Rails 测试中不起作用 [英] ActiveRecord Rollback does not work in Rails test

查看:53
本文介绍了ActiveRecord 回滚在 Rails 测试中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

以下测试用例失败(使用 shoulda 库,但使用基本 Test::Unit 的相同测试失败):

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

但是在控制台上:

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

推荐答案

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

You should turn off transactions in your test case:

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

这篇关于ActiveRecord 回滚在 Rails 测试中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆