2010-07-22 36 views
0

我最初編寫如下測試代碼;在lambda {}中創建每個記錄的記錄不會更改RSpec中的記錄數

fixtures :records 

it "should double number of records " do 
    @payment_transactions = PaymentTransaction.find :all 
    length = @payment_transactions.length 

    lambda{ 
    @payment_transactions.each{ |pt| 
     PaymentTransaction.create(:data => pt.data) 
    } 
    }.should change{PaymentTransaction.find(:all).length}.from(length).to(length * 2) 
end 
=> 
# 'PaymentTransaction should double number of records ' FAILED 
# result should have been changed to 202, but is now 101 

但是這並沒有出於某種原因。

然後,我把lambda和每個其他方式都像波紋管一樣,因爲我猜測數據在每一次都沒有任何改動。

it "should increase number of records by one for each time when creating a new record" do 
    length = PaymentTransaction.find(:all).length 

    @payment_transactions.each{ |ph| 
    lambda{ 
     PaymentTransaction.create(:data => ph.data) 
    }.should change{PaymentTransactionfind(:all).length}.by(1) 
    } 

end 

有人知道是什麼原因導致第一個人的奇怪行爲?

回答

1

我可以建議你試試這個代碼:

it "should double number of records " do 

    initial_count = PaymentTransaction.count 

    lambda{ 
    PaymentTransaction.all.each{ |pt| 
     PaymentTransaction.create(:data => pt.data) 
    } 
    }.should change(PaymentTransaction, :count).from(initial_count).to(initial_count * 2) 
end 
相關問題