2010-07-22 50 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