[英]How to test if an ActiveRecord association is being used with RSpec?
[英]What's a nice way to verify within a unit test that an ActiveRecord transaction is being used?
我有一个执行几种数据库操作的类,并且我想编写一个单元测试,以验证这些操作均在事务内执行。 有什么好的清洁方法?
这是一些示例代码,说明我正在测试的类:
class StructureUpdater
def initialize(structure)
@structure = structure
end
def update_structure
SeAccount.transaction do
delete_existing_statistics
delete_existing_structure
add_campaigns
# ... etc
end
end
private
def delete_existing_statistics
# ...
end
def delete_existing_structure
# ...
end
def add_campaigns
# ...
end
end
Rspec允许您断言特定块范围内的数据已更改。
it "should delete existing statistics" do
lambda do
@structure_updater.update_structure
end.should change(SeAccount, :count).by(3)
end
...或一些类似的东西,具体取决于您的架构外观,等等。不确定在delete_existing_statistics中到底发生了什么,因此请相应地更改change子句。
编辑:首先,我不明白这个问题,很抱歉。 您可以尝试断言以下内容,以确保这些调用以给定顺序发生(再次使用RSpec):
编辑:您无法在对该事务内的调用有期望的测试中断言对某个事务的期望。 我能想到的最接近的是:
describe StructureUpdater do
before(:each) do
@structure_updater = StructureUpdater.new(Structure.new)
end
it "should update the model within a Transaction" do
SeAccount.should_receive(:transaction)
@structure_updater.update_structure
end
it "should do these other things" do
@structure_updater.should_receive(:delete_existing_statistics).ordered
@structure_updater.should_receive(:delete_existing_structure).ordered
@structure_updater.should_receive(:add_campaigns).ordered
@structure_updater.update_structure
end
end
一个更重的尝试:另一个小技巧是迫使事务块中的后续方法调用之一引发,并断言数据库中没有任何变化。 例如,假设Statistic是一个模型,并且delete_existing_statistics会更改数据库中Statistic的计数,那么,如果稍后在事务中引发的异常回滚了该更改,则您可以知道该事务中发生了调用。 就像是:
it "should happen in a transaction" do
@structure_updater.stub!(:add_campaigns).and_raise
lambda {@structure_updater.update_structure}.should_not change(Statistic, :count)
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.