添加到Date类的方法的NoMethodError

时间:2015-02-14 05:11:13

标签: ruby-on-rails ruby unit-testing testcase

我在Date类中添加了两个方法,并将其放在lib/core_ext中,如下所示:

class Date
  def self.new_from_hash(hash)
    Date.new flatten_date_array hash
  end

  private
  def self.flatten_date_array(hash)
     %w(1 2 3).map { |e| hash["date(#{e}i)"].to_i }
  end
end

然后创建了一个测试

require 'test_helper'

class DateTest < ActiveSupport::TestCase
  test 'the truth' do
    assert true
  end

  test 'can create regular Date' do
    date = Date.new
    assert date.acts_like_date?
  end

  test 'date from hash acts like date' do
    hash = ['1i' => 2015, '2i'=> 'February', '3i' => 14]
    date = Date.new_from_hash hash
    assert date.acts_like_date?
  end
end

现在我收到的错误是:Minitest::UnexpectedError: NoMethodError: undefined method 'flatten_date_array' for Date:Class

我是否错误地定义了我的方法?我甚至尝试在flatten_date_array内移动new_from_hash方法,但仍然遇到错误。我尝试在MiniTest中创建一个测试并得到同样的错误。

1 个答案:

答案 0 :(得分:1)

私人不会为类方法工作,并使用self。

class Date
  def self.new_from_hash(hash)
    self.new self.flatten_date_array hash
  end

  def self.flatten_date_array(hash)
     %w(1 2 3).map { |e| hash["date(#{e}i)"].to_i }
  end
end
相关问题