与此问题相关:custom transaction doesn't work with database_cleaner in rspec
有什么地方是人们不想用 requires_new 启动 TX 的吗? (嵌套 TX)
ModelObject.transaction(requires_new: true)
如果是这样的话,这应该是默认的吧。
顺便说一句,这就是使用默认事务策略时,当代码的正常执行路径成功时,带有回滚的 rspec 测试将失败的原因。
这是我的 DatabaseCleaner 设置。运行 Rails 4.
RSpec.configure do |config|
config.add_setting(:seed_tables)
config.seed_tables = %w(global_options shoot_types)
config.before(:suite) do
DatabaseCleaner.clean_with(:truncation, except: config.seed_tables)
end
config.before(:each) do
DatabaseCleaner.strategy = :transaction
end
config.before(:each, js: true) do
DatabaseCleaner.strategy = :truncation, {except: config.seed_tables}
end
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
end
最佳答案
In order to get a ROLLBACK for the nested transaction you may ask for a real sub-transaction by passing requires_new: true. If anything goes wrong, the database rolls back to the beginning of the sub-transaction without rolling back the parent transaction. If we add it to the previous example:
Most databases don’t support true nested transactions. At the time of writing, the only database that we’re aware of that supports true nested transactions, is MS-SQL. Because of this, Active Record emulates nested transactions by using savepoints on MySQL and PostgreSQL. See dev.mysql.com/doc/refman/5.6/en/savepoint.html for more information about savepoints.
http://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html
关于rspec - Rails 中的 TX 不应该有 requires_new : true 的任何原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20409989/