require 'test_helper'

class MailHandlerTest < ActionController::IntegrationTest
  context "The MailHandler should accept incoming emails generated by" do
    setup do
      @asker = User.generate_with_protected!
      @responder = User.generate_with_protected!
      @project = Project.generate!
      @role = Role.generate!(:permissions => [:add_issue_notes, :edit_issues])
      Member.generate!(:principal => @asker, :roles => [@role], :project => @project)
      Member.generate!(:principal => @responder, :roles => [@role], :project => @project)
      @issue = Issue.generate_for_project!(@project)
      @question = Question.new(:issue => @issue, :author => @asker, :assigned_to => @responder)
      @issue.journal_notes = "Test"
      @issue.extra_journal_attributes = { :question => @question }
      assert @issue.save
      @question_journal = @issue.journals.last

    end
    
    should 'the asked question email' do
      @mail = QuestionMailer.create_asked_question(@question_journal.reload)

      # Fake out a reply
      @reply = TMail::Mail.new
      @reply.subject = @mail.subject
      @reply.from = @responder.mail
      @reply.body = "This is an update"

      journal = MailHandler.receive(@reply.encoded)
      assert journal.is_a?(Journal), "MailHandler did not create a Journal"
      assert_equal "This is an update", journal.notes
    end

    
    should 'the answered question email' do
      @issue.reload
      @issue.journal_notes = "Answer"
      @issue.journal_user = @responder
      assert @issue.save
      @answer = @issue.journals.last
      
      @mail = QuestionMailer.create_answered_question(@question, @answer)

      # Fake out a reply
      @reply = TMail::Mail.new
      @reply.subject = @mail.subject
      @reply.from = @responder.mail
      @reply.body = "This is an update"

      journal = MailHandler.receive(@reply.encoded)
      assert journal.is_a?(Journal), "MailHandler did not create a Journal"
      assert_equal "This is an update", journal.notes
    end
  end
end
