我一直在尝试测试要求嵌套事务回滚父事务的行为,但是它没有按预期工作。
根据其他SO Q/A和documentation,您需要:
对我执行的子交易执行transaction(joinable: false, requires_new: true)
:
def some_method(child_transaction: false)
Conn.transaction(joinable: !child_transaction, requires_new: child_transaction) do
# Some Active reciord stuff
end
end
您需要turn off transactions来进行我通过助手进行的测试:
config.around(:each, use_transactional_fixtures: false) do |example|
self.use_transactional_tests = false
example.run
self.use_transactional_tests = true
end
并按如下方式使用:
it 'does not create a record', use_transactional_fixtures: false do
expect { subject }.not_to(change(ModelName, :count))
end
现在,我已经完成了这项工作,并通过其中一项测试来证明交易有效 通过,问题在于用于证明嵌套交易不能按预期完成的规范。
我正在测试的位是这样的:
def some_method
ActiveRecord::Base.transaction do
record = Model.new
# some code
record.method_which_contains_transaction(child_transaction: true)
# some more code
end
end
class Model < ActiveRecord::Base
def method_which_contains_transasction(child_transaction: false)
transaction(joinable: !child_transaction, requires_new: child_transaction) do
stubbed_method
end
end
end
规格类似于 :
describe 'some_method' do
before do
allow(Model).to
receive(:stubbed_method).and_raise(ActiveRecord::Rollback)
cost
end
it 'does not create a record', use_transactional_fixtures: false do
expect { subject }.not_to(change(Model, :count))
end
end
我只是不确定为什么它不起作用,我显然做错了什么,我只是不知道它是什么,为什么子事务似乎不引起父事务的回滚,如符合我的期望?
规范失败,出现类似expected Model count to not change but it did