views:

13

answers:

1

I initially wrote testing code like the following;

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

But this didn't work for some reason.

Then, I put lambda and .each other way round like bellow because I guessed data munupilation in .each didn't do anything.

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

Does someone know what causes first one's strange behaviour?

A: 

May I suggest you to try this code:

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
Marcus Derencius