Rails 3 - 验证时间存在

时间:2012-04-29 10:46:10

标签: ruby ruby-on-rails-3 validation rspec ruby-on-rails-3.2

我有一个带有Time属性的模型。我想检查时间不能为空(更好的选择可能是检查输入是时间但我不知道如何处理)。我尝试了这个验证:

#  id              :integer         not null, primary key
#  school_class_id :integer
#  meeting_time    :time
class Meeting < ActiveRecord::Base                                                    
  validates :meeting_time,
              :presence => { :message => "can't be empty!" }                                                            
end

然后我试图在规范中检查这个并且这失败了(空闲时间没问题,但不应该这样)。我做错了什么?

Rspec的:

#  id              :integer         not null, primary key
#  school_class_id :integer
#  meeting_time    :time

require 'spec_helper'

describe Meeting do
  before(:each) do
    @class = FactoryGirl.create( :school_class )
    @attr_meeting = {
      :meeting_theme => 'Text is here',
      :meeting_date => "#{Date.today}",
      :meeting_time => "#{Time.now}",
      :meeting_room => '1234'
    }
  end

  describe "Validations" do
    describe "Rejection" do
      it "should reject blank time" do
        wrong_attr = @attr_meeting.merge( :meeting_time => "  " )
        @class.meetings.build( wrong_attr ).should_not be_valid
      end
    end
  end
end

错误:

 Meeting Validations Rejection should reject blank time
     Failure/Error: @class.meetings.build( wrong_attr ).should_not be_valid
       expected valid? to return false, got true

1 个答案:

答案 0 :(得分:1)

在您的示例中,您将" "分配给meeting_time,而不是nil""。但是Time对象可以通过非空,甚至空白字符串成功生成。将meeting_time设置为""nil可以解决您的问题。

也许我不完全理解某些东西,但我认为这不是非常合乎逻辑且可预测的行为。需要看看来源。