如何为此before_validation回调编写rspec测试?

时间:2014-02-10 02:07:08

标签: ruby-on-rails ruby-on-rails-3 rspec callback

我有一个使用before_validation回调的模型,通过集成表单中的call_time_time和call_time_date字段来设置call_time属性。

class Attendance < ActiveRecord::Base
  attr_accessor :call_time_date, :call_time_time
  before_validation :set_call_time

  def set_call_time
    if call_time_date && call_time_time
      d = Date.parse call_time_date
      t = Time.parse call_time_time
      self.call_time = Time.local d.year, d.month, d.day, t.hour, t.min
    end
  end
end

set_call_time方法仍然很不发达(它以空字段失败),但在我再做之前,我希望它能够正确测试。

这是我目前的测试。它通过了,但我实际上希望它失败,我不明白它为什么会过去。

describe Attendance
  it "should be invalid if the call_time is not set in the parameters" do
    attendance = FactoryGirl.build :attendance, call_time: nil, call_time_time: nil, call_time_date: nil
    attendance.valid? #To trigger before_validation callback
    attendance.should_not be_valid
  end
end

,这是相关的工厂

FactoryGirl.define do
  factory :attendance do
    call_time "2012-06-01 15:00"
  end
end

似乎很多人在测试before_validation回调时遇到问题,所以任何帮助都会受到赞赏。

1 个答案:

答案 0 :(得分:1)

在您的代码中,您目前还没有验证任何内容......我的意思是:您还应该添加类似

的内容
validates_presence_of :call_time

到您的模型,以便触发验证

目前您只执行set_call_time方法。更不用说了!

相关问题