0

我正在编写一个应用程序,用户必须年满 13 岁才能加入。我的设置是DeviseUnicorn server,这是我的User模型:

用户.rb

  attr_accessible :birthday

  validates_presence_of :birthday

  validate :is_certain_age

  private

  def is_certain_age
    if self.birthday
      errors.add(:base, 'You need to be at least 13.') if self.birthday > Date.today.year - 13
    end
  end

我试图在浏览器中对此进行测试,但是当我提交注册表单时,它会发布并且仍然不创建用户或不创建用户。我不知道发生了什么,因为独角兽服务器不会像 WEBrick 那样告诉我参数。这就是我得到的全部:

127.0.0.1 - - [22/Jun/2013 11:21:12] "POST /users HTTP/1.1" 200 - 0.3460

我对用户的 Rspec 测试显示这些失败:

 User 
   Failure/Error: it { should be_valid }
   NoMethodError:
   undefined method `to_datetime' for 2000:Fixnum

注意:使用应该匹配器

User valid user age 
   Failure/Error: it { should ensure_inclusion_of(:birthday).in_range(13..150) }
   Did not expect errors to include "is not included in the list"..... 
   ...when birthday is set to 12, got error: 

我做错了什么?

4

1 回答 1

1

你想要的是:

errors.add(:base, 'You need to be at least 13.') if self.birthday > Date.today - 13.years

您将DateTime( self.birthday) 与FixNum( )2000的结果进行比较Date.today.year - 13,而在我上面的代码中:Date.today - 13.years,结果也是 DateTime 。

于 2013-06-22T16:08:34.183 回答