vendredi 29 septembre 2017

Ruby: Use Date.Parse to determine if date is erroneous

I have test file that has a list of tests to run on my other file which demand an assert for an erroneous date

require "minitest/autorun"
require "./simple_date"

describe SimpleDate do
  it "works as expected" do
    assert_raises { SimpleDate.new(1969, 12, 31) }
    assert_raises { SimpleDate.new(2016, 1, 32) }
    assert_raises { SimpleDate.new(2016, 2, 30) }
    assert_raises { SimpleDate.new(2016, 3, 32) }
    assert_raises { SimpleDate.new(2016, 4, 31) }
    # ... there are more this is just a sample
  end

This part of my other file works:

require 'date'

class SimpleDate
  attr_reader :year, :month, :day
  def initialize(year, month, day) 
    if !year.between?(1970, 2020)
      raise 'Error: Year not betwen 1970 and 2020'
    elsif !month.between(1, 12)
      raise 'Error: Month not between 1 and 12'
    elsif !day.between?(1, 31)
      raise 'Error: Day not between 1 and 31'
    end    

This part of my other file does not work.

begin
  Date.parse(year, month, day)
rescue
  raise 'Date Format Error'
end

Can you please help me better format my second part so that it will pass the tests?

Aucun commentaire:

Enregistrer un commentaire