Ruby:使用Date.Parse来确定日期是否错误

时间:2017-09-29 14:12:10

标签: ruby function if-statement automated-tests

我有一个测试文件,其中有一个测试列表要在我的另一个文件上运行,该文件要求断言错误的日期

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

我的其他文件的这一部分有效:

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    

我的其他文件的这一部分不起作用。

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

你能帮我更好地格式化我的第二部分,以便通过测试吗?

2 个答案:

答案 0 :(得分:3)

如果您想使用Date#parse检查输入,请使用它:

class SimpleDate
  MESSAGE = 'Date Format Error'
  def initialize(year, month, day)
    # explicitly reject before unix epoch
    raise MESSAGE if !year.between(1970, 2020)
    begin
      Date.parse "#{year}/#{month}/#{day}"
    rescue ArgumentError
      raise MESSAGE
    end
  end
end

答案 1 :(得分:0)

谢谢mudasowba,我不得不稍微修改你的代码:

class SimpleDate
  MESSAGE = 'Date Format Error'

  def initialize(year, month, day) 
    raise MESSAGE if !year.between?(1970, 2020)
    begin
      Date.parse "#{year}/#{month}/#{day}"
    rescue ArgumentError
      raise MESSAGE
    end
  end
end

你为我节省了很多时间并提高了我的理解力。谢谢!