# The purpose of this 'test' is to render emails to disk,
# So that a developer can look in tmp/emails and open them up and verify that they look OK
# Also, to have Jenkins archive them to make it easier to check if a build look OK

require "spec_helper"

describe "RenderMailers", :slow => true do

  let(:user) { FactoryGirl.create(:user) }

  before(:each) do
    @filename = nil # set this on your test to pin the filename; i just make it the name of the mailer method responsible for sending the mail
  end

  describe "UserMailer emails" do

    before(:each) do
      user.update_email = "my_new_email@jamkazam.com"
      UserMailer.deliveries.clear
    end

    after(:each) do
      UserMailer.deliveries.length.should == 1
      mail = UserMailer.deliveries[0]
      save_emails_to_disk(mail, @filename)
    end

    it { @filename="welcome_message"; UserMailer.welcome_message(user).deliver }
    it { @filename="confirm_email"; UserMailer.confirm_email(user, "/signup").deliver }
    it { @filename="password_reset"; UserMailer.password_reset(user, '/reset_password').deliver }
    it { @filename="password_changed"; UserMailer.password_changed(user).deliver }
    it { @filename="updated_email"; UserMailer.updated_email(user).deliver }
    it { @filename="updating_email"; UserMailer.updating_email(user).deliver }
  end

  describe "InvitedUserMailer emails" do

    let(:user2) { FactoryGirl.create(:user) }
    let(:invited_user) { FactoryGirl.create(:invited_user, :sender => user2) }
    let(:admin_invited_user) { FactoryGirl.create(:invited_user) }

    before(:each) do
      InvitedUserMailer.deliveries.clear
    end

    after(:each) do
      UserMailer.deliveries.length.should == 2
      # NOTE! we take the second email, because the act of creating the InvitedUser model
      # sends an email too, before our it {} block runs.  This is because we have an InvitedUserObserver
      mail = InvitedUserMailer.deliveries[1]
      save_emails_to_disk(mail, @filename)
    end

    it { @filename="friend_invitation"; InvitedUserMailer.deliveries.clear; InvitedUserMailer.friend_invitation(invited_user).deliver }
    it { @filename="welcome_betauser"; InvitedUserMailer.welcome_betauser(admin_invited_user).deliver }
  end

end

def save_emails_to_disk(mail, filename)
  # taken from: https://github.com/originalpete/actionmailer_extensions/blob/master/lib/actionmailer_extensions.rb
  # this extension does not work with ActionMailer 3.x, but this method is all we need

  if filename.nil?
    filename = mail.subject
  end

  email_output_dir = 'tmp/emails'
  FileUtils.mkdir_p(email_output_dir) unless File.directory?(email_output_dir)
  filename = "#{filename}.eml"
  File.open(File.join(email_output_dir, filename), "w+") {|f|
    f << mail.encoded
  }
end