Peter
Peter

Reputation: 447

Does Rails' assert_difference ignore some changes?

I have a test in which I complete a payment to a user who has one account. The account contains the balance and has many transactions.

On payment completion, a transaction is created and the balance on the account is updated.

Using assert_difference to check the number of transactions changes gives the expected result. However using assert_difference to check that the balance has changed does not. I can see the SQL to update the balance in my log but the assertion thinks it has not changed.

I am completely confused, can anyone please explain?

Thanks in advance.

This passes:

assert_difference("a_user.account.transactions.count", 1) do
  # Process payment
end

This fails, saying there is no change:

assert_difference("a_user.account.balance", 250.00) do
  # Process payment
end

This is the failure messge from the assertion:

"a_user.account.balance" didn't change by 250.0.
<300.0> expected but was
<50.0>.

This is the relevant SQL from the log file:

  User Load (0.4ms)   SELECT * FROM `users` WHERE (`users`.`id` = 108093344) 
  Account Load (0.2ms)   SELECT * FROM `accounts` WHERE (`accounts`.user_id = 108093344) LIMIT 1
  Transaction Columns (1.5ms)   SHOW FIELDS FROM `transactions`
  Transaction Create (0.3ms)   INSERT INTO `transactions` (`created_at`, `updated_at`, `amount`, `account_id`, `detail`) VALUES('2011-02-01 17:15:21', '2011-02-01 17:15:21', 250.0, 956948796, 'Payment completed')
  Account Load (0.2ms)   SELECT * FROM `accounts` WHERE (`accounts`.`id` = 956948796) 
  Account Update (0.2ms)   UPDATE `accounts` SET `updated_at` = '2011-02-01 17:15:21', `balance` = 300.0 WHERE `id` = 956948796

Upvotes: 3

Views: 1198

Answers (1)

egze
egze

Reputation: 3236

Try to reload the record

assert_difference("a_user.account.reload.balance", 250.00) do
  # Process payment
end

Upvotes: 6

Related Questions