【问题标题】:Ruby: Use Date.Parse to determine if date is erroneousRuby:使用 Date.Parse 确定日期是否错误
【发布时间】:2017-09-29 14:12:09
【问题描述】:

我有一个测试文件,其中包含要在我的另一个文件上运行的测试列表,这些测试需要一个错误日期的断言

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

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

【问题讨论】:

    标签: ruby function if-statement automated-tests


    【解决方案1】:

    如果你想使用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
    

    【讨论】:

    • 如果您想使用Date 来检查有效日期,请使用Date.valid_date?(y, m, d) ;-)
    • 不幸的是,Date::parse 的区别不大:Date.parse("1111") => #<Date: 2017-11-11 ((2458069j,0s,0n),+0s,2299161j)>。 @Stefan,Date#valid 来自 Rails 吗?
    • 来自标准库的@CarySwoveland:Date::valid_date?
    【解决方案2】:

    谢谢 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
    

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

    【讨论】:

    • 我已经更新了我的答案,请删除这个答案,因为它与 SO 的规则相矛盾。
    猜你喜欢
    • 1970-01-01
    • 2011-07-25
    • 1970-01-01
    • 2022-10-15
    • 2018-10-06
    • 1970-01-01
    • 2013-10-08
    • 2014-12-14
    • 2015-06-03
    相关资源
    最近更新 更多