如何使用 rspec 来测试交易块
How to use rspec to test a transaction block
我正在将一些代码包装在事务块中,即
Tip.transaction do
...make changes to lots of tips...
end
我这样做的原因是我想确保在提交到数据库之前完成所有更改。如何使用rspec测试如果在事务完成前发生故障,数据库会回滚到之前的状态?
您可以只检查没有提示被保存到失败的情况下。这里唯一的疑问是 失败提示 对您意味着什么,因为这就是您将在测试中重现的内容。一个普通的例子:
# app/models/tip.rb
before_save :fail_if_bad_amoun
def fail_if_bad_amount
fail BadAmount if amount == 'bad'
end
def self.process(tips)
Tip.transaction do
tips.all? &:save
end
end
# spec/models/tip_spec.rb
it "does not commit in case of failure in one of the tips" do
good_tip = Tip.new(amount: 1_000)
bad_tip = Tip.new(amount: 'bad')
expect do
Tip.process([good_tip, bad_tip])
end.not_to change { Tip.count }
end
我正在将一些代码包装在事务块中,即
Tip.transaction do
...make changes to lots of tips...
end
我这样做的原因是我想确保在提交到数据库之前完成所有更改。如何使用rspec测试如果在事务完成前发生故障,数据库会回滚到之前的状态?
您可以只检查没有提示被保存到失败的情况下。这里唯一的疑问是 失败提示 对您意味着什么,因为这就是您将在测试中重现的内容。一个普通的例子:
# app/models/tip.rb
before_save :fail_if_bad_amoun
def fail_if_bad_amount
fail BadAmount if amount == 'bad'
end
def self.process(tips)
Tip.transaction do
tips.all? &:save
end
end
# spec/models/tip_spec.rb
it "does not commit in case of failure in one of the tips" do
good_tip = Tip.new(amount: 1_000)
bad_tip = Tip.new(amount: 'bad')
expect do
Tip.process([good_tip, bad_tip])
end.not_to change { Tip.count }
end