ActiveRecord 回滚在 Rails 测试中不起作用
抛出 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该关闭测试用例中的事务:
[编辑:根据 @Conrad 的评论,它应该是
transactionAL
]You should turn off transactions in your test case:
[edit: as per @Conrad's comment it should be
transactionAL
]实际上调用的方法如下:
不是
self.use_transaction_fixtures
(注意缺少'al')Actually the method to call is as follows:
not
self.use_transaction_fixtures
(note the missing 'al')