Topic: Cant make my test to work...

I have this class:

class ForSale < ActiveRecord::Base
belongs_to :user
  def sold!(sold_at = DateTime.now)
    if self.sold_on.nil?
      self.sold_on = sold_at
      self.save
      user.reload #<-------this doesnt work????
    else
      false #add error message
    end     
  end
end

and this unit test:

  def test_sold
    guy = users(:guy)
    rebel= for_sales(:guy_rebel)
    assert_equal 0, guy.sales.size
    rebel.sold!
    #guy.reload <--- this is the problematic line!!!!
    assert_equal 1, guy.sales.size
  end

My last assertion doesnt work unless I reload the variable (commented line). So here are my questions:
- is there a better way to do the sold! function?
- why the user.reload code doesnt seem to work, but if I call reload on the User object (guy) it works.
- logicaly, keeping the User up to date when an item is sold should be the job of the ForSale class. So how can I do this?

Thanks a lot!

Re: Cant make my test to work...

From my understanding, although "guy" and "user" are the same database record, they are not the same Ruby object. Calling reload on a model object just reloads that one object's instance variables with the contents of the database. The ForSale object knows nothing about the 2nd instance "guy" in the test, which doesn't get reloaded.

You can either stick with the reload in the test. Or you can set the "rebel" variable first and fetch the "guy" from rebel.user and leave the reload in the model. It will then be the same object which should be reloaded. There may be a better solution, but I don't know of one.

Railscasts - Free Ruby on Rails Screencasts

Re: Cant make my test to work...

Thanks, the following code works:

def ForSale <activerecord:base
  def sold!(sold_at = DateTime.now)
    if self.sold_on.nil?
      self.sold_on = sold_at
      self.save
      user.reload
    else
      false #add error message
    end     
  end
end

with this test:

  def test_sold
    rebel= for_sales(:guy_rebel)
    #make sure there are no products already sold
    assert_equal 0, rebel.user.sales.size
    #sell the item
    rebel.sold!
    #now there is one product sold
    assert_equal 1, rebel.user.sales.size
    #nothing is lost
    assert_equal rebel.user.for_sales.size + 1, rebel.user.sales.size + rebel.user.for_sales.size
  end

Thanks again, at least its working!

But I dont understand perfectly your explanation.. anyone can give it a try?