[英]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.