Created
April 13, 2012 13:43
-
-
Save peterhellberg/2376948 to your computer and use it in GitHub Desktop.
Testing the WeekNumber class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# encoding: utf-8 | |
class WeekNumber | |
attr_reader :cweek, :year | |
def initialize(cweek = Date.today.cweek, year = Date.today.year) | |
@year = year.to_i | |
@cweek = cweek.to_i | |
if @cweek > WeekNumber.weeks_in(@year) | |
raise ArgumentError, 'Invalid cweek' | |
end | |
end | |
def self.weeks_in(year) | |
Date.new(year, 12, 28).cweek # magick date! | |
end | |
def self.by_date(date) | |
new date.cweek, date.year | |
end | |
def self.by_key(key) | |
new(*key.split('v').reverse) | |
end | |
def key | |
"#{year}v#{cweek}" | |
end | |
def label | |
"Vecka #{cweek} #{year}" | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# encoding: utf-8 | |
require_relative "spec_helper" | |
require_relative "../lib/week_number.rb" | |
describe WeekNumber do | |
subject { WeekNumber } | |
let(:today) { Date.today } | |
let(:future) { today + 1337 } | |
let(:year) { today.year } | |
let(:cweek) { today.cweek } | |
let(:weeks_this_year) { Date.new(today.year, 12, 28).cweek } | |
let(:current_key) { "#{year}v#{cweek}" } | |
let(:current_label) { "Vecka #{cweek} #{year}" } | |
it "doesn’t allow invalid week numbers" do | |
-> { subject.new(weeks_this_year + 1) }.must_raise ArgumentError | |
end | |
it "returns a key for a given week" do | |
subject.new(1).key.must_equal "#{year}v1" | |
subject.new(2,1990).key.must_equal "1990v2" | |
subject.new.key.must_equal current_key | |
end | |
it "returns a label for a given week" do | |
subject.new(1).label.must_equal "Vecka 1 #{year}" | |
subject.new(2,1990).label.must_equal "Vecka 2 1990" | |
subject.new.label.must_equal current_label | |
end | |
it "returns the key for today" do | |
subject.by_date(today).key.must_equal current_key | |
end | |
it "returns the key for a date in the future" do | |
subject.by_date(future).key.must_equal "#{future.year}v#{future.cweek}" | |
end | |
it "returns a label for a given key" do | |
subject.by_key(current_key).label.must_equal current_label | |
subject.by_key('1999v52').label.must_equal "Vecka 52 1999" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment