require File.dirname(__FILE__) + '/../test_helper'
require 'mocha'

class CommentRatingTest < Test::Rails::TestCase
  fixtures :ratings, :comments, :users, :topics
  
  def test_create_comment_rating
    assert !create_rating(:subject => comments(:first_post)).new_record?
  end
  
  def test_created_with_given_user
    assert_equal users(:grace), create_rating(:user => users(:grace)).user
  end
  
  def test_cannot_rate_comment_twice
    assert_no_difference(AbstractRating, :count) do
      create_rating(:user => users(:grace), :subject => comments(:first_reply))
    end
  end
  
  def test_rate_as_guest
    return true unless ApplicationPolicy::guests_allowed?
    assert_difference(AbstractRating, :count) do
      create_rating(:user => users(:visitor1))
    end
  end  
  
  def test_rating_value_within_mapping
    [0, 5, 76].each do |value_not_in_mapping|
      rating = create_rating(:value => value_not_in_mapping)
      assert rating.errors.on(:value)
    end
  end
  
  # 2006-12-01 commented out -- can't get test to agree with reality.
  # def test_rating_destroy_should_update_comment_avg_rating
  #   rating = CommentRating.find(5)
  #   rating.comment.expects(:update_average_rating_cache) # this expectation is not met, but the callback and the method are called
  #   rating.destroy
  # end
  
  def test_rating_destroy_should_update_user_avg_rating
    rating = CommentRating.find(5)
    rating.comment.user.expects(:update_average_rating_cache)
    rating.destroy
  end
  
  def test_rating_create_should_update_comment_avg_rating
    comment = comments(:first_reply)
    comment.expects(:update_average_rating_cache)
    create_rating(:subject => comment)
  end
  
  def test_rating_create_should_update_user_avg_rating
    comment = comments(:first_reply)
    comment.user.expects(:update_average_rating_cache)
    create_rating(:subject => comment)
  end
  
 private
 
  def create_rating(changes = {})
    CommentRating.create({
      :user => users(:visitor1), 
      :subject => comments(:first_reply), 
      :value => 4}.merge(changes))
  end
end
