Using Rails, problem testing has_many relationship

Posted by east on Stack Overflow See other posts from Stack Overflow or by east
Published on 2010-04-11T04:44:13Z Indexed on 2010/04/11 4:53 UTC
Read the original article Hit count: 345

The summary is that I've code that works when manually testing, but isn't doing what I would think it should when trying to build an automated test. Here are the details: I've two models: Payment and PaymentTranscation.

class Payment ...
  has_many :transactions, :class_name => 'PaymentTransaction'

class PaymentTranscation ...
  belongs_to payment

The PaymentTransaction is only created in a Payment model method, like so:

def pay_up
  ...
  transactions.create!(params...)
  ...
end

I've manually tested this code, inspected the database, and everything works well. The failing automated test looks like this:

  def test_pay_up
    purchase = Payment.new(...)
    assert purchase.save
    assert_equal purchase.state, :initialized.to_s
    assert purchase.pay_up # this should create a new PaymentTransaction...
    assert_equal purchase.state, :succeeded.to_s
    assert_equal purchase.transactions.count, 1  # FAILS HERE; transactions is an empty array
  end

If I step through the code, it's clear that the PaymentTransaction is getting created correctly (though I can't see it in the database because everything is in a testing transaction). What I can't figure out is why transactions is returning an empty array in the test when I know a valid PaymentTransaction is getting created. Anybody have some suggestions?

Thanks in advance, east

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about testing