views:

229

answers:

2

How to test the following example?

class Post < ActiveRecord::Base
  belongs_to :discussion  

  def after_save   # or after_create
    discussion.touch
  end
end

EDIT: I have found a nicer way to write the code above.

  class Post < ActiveRecord::Base
      belongs_to :discussion, :touch => true
    end
A: 

You can mock the #touch call, or verify the effects of your callback on it.

it "should touch the discussion" do
  original_updated_at = @discussion.updated_at
  @post.save!
  @post.discussion.updated_at.should_not_be == original_updated_at
end
François Beausoleil
+1  A: 

You can set a message expectation:

  it "should touch the discussion" do
    @post = Factory.build(:post)
    @post.discussion.should_receive(:touch)
    @post.save!
  end

This examples uses Factory Girl, but you could use fixtures or mocks as well.

zetetic
It always amazes me how simple and elegant Ruby/Rails/Rspec is.
Ermin