DanielBlanco
1/30/2017 - 9:43 PM

Test

Test

require 'test_helper'

# Make sure to turn `self.use_transactional_fixtures` to false.
#
# Also, run this before testing:
#   $ rake db:test:prepare && rake db:test:preload && rake log:clear
#
class AppointmentRaceConditionTest < ActiveSupport::TestCase

  context ".build_new!" do
    setup do
      setup_appointment_attributes
    end

    should "not allow conflicts" do
      # disconnect before forking
      ActiveRecord::Base.connection.disconnect!

      process1, process2 = 2.times.map do |i|
        ForkBreak::Process.new do
          # DB connection per thread
          ActiveRecord::Base.establish_connection

          student_id = (i == 1 ? student1.id : student2.id)
          Rails.logger.debug "Student ID: #{student_id}"

          begin
            app = Appointment.build_new!(
              @appointment_attributes,
              @calendar_item_attributes,
              [student_id, advisor.id],
              reject_organizer_conflicts: true
            )
          end
        end
      end

      process1.run_until(:bp).wait
      process2.run_until(:bp).wait

      process1.finish.wait
      process2.finish.wait

      # The parent process also needs a connection
      ActiveRecord::Base.establish_connection

      assert false, "check log/test.log"
    end
  end

  private

  def setup_appointment_attributes
    @appointment_attributes = {
      location_name: location.name,
      appointment_type: "advising",
      send_email_reminder: "",
      send_sms_reminder: "",
      comments: "Be on time.",
      group_id: group.id,
      creation_type: "Scheduled",
      student_service_ids: [student_service_advisor.id]
    }
  end

  def setup_calendar_item_attributes
    @calendar_item_attributes = {
      location: location.name,
      begin_date_time: aft_begin_time,
      end_date_time: aft_end_time,
      organizer_id: advisor.id
    }
  end
end