ruralocity
8/2/2012 - 3:21 AM

Calculate the date range for the school year for a given date.

Calculate the date range for the school year for a given date.

require 'date'
require 'minitest/autorun'

class SchoolYear
  def self.date_range(day=Date.today.to_s)
    d = Date.parse(day)
    if d.month >= 8
      start_year = d.year
      end_year = d.year + 1
    else
      start_year = d.year - 1
      end_year = d.year
    end

    Date.parse("#{start_year.to_s}-08-01")..Date.parse("#{end_year.to_s}-07-31")
  end
end

class SchoolYearTest < MiniTest::Spec
  describe "school year" do
    describe "today's date" do
      it "includes the most recent august 1" do
        SchoolYear.date_range.must_include Date.parse('2012-08-01')
      end

      it "does not include the most recent july 31" do
        SchoolYear.date_range.wont_include Date.parse('2012-07-31')
      end

      it "includes today's date" do
        SchoolYear.date_range.must_include Date.today
      end

      it "includes the next july 31" do
        SchoolYear.date_range.must_include Date.parse('2013-07-31')
      end

      it "does not include the next future august 1" do
        SchoolYear.date_range.wont_include Date.parse('2013-08-01')
      end
    end

    describe "the school year for 2010-09-30" do
      it "knows the school year started on 2010-08-01" do
        SchoolYear.date_range('2010-09-30').first.to_s.must_equal '2010-08-01'
      end

      it "knows the school year ended on 2011-07-31" do
        SchoolYear.date_range('2010-09-30').last.to_s.must_equal '2011-07-31'
      end
    end

    describe "the school year for 2013-08-01" do
      it "knows the school year starts on 2013-08-01" do
        SchoolYear.date_range('2013-09-30').first.to_s.must_equal '2013-08-01'
      end

      it "knows the school year ends on 2013-07-31" do
        SchoolYear.date_range('2013-07-31').last.to_s.must_equal '2013-07-31'
      end
    end

    describe "the school year for 2013-07-31" do
      it "knows the school year starts on 2012-08-01" do
        SchoolYear.date_range('2013-07-31').first.to_s.must_equal '2012-08-01'
      end

      it "knows the school year ends on 2013-07-31" do
        SchoolYear.date_range('2013-07-31').last.to_s.must_equal '2013-07-31'
      end
    end
  end
end