【问题标题】:How do I write an rspec test for this before_validation callback?如何为此 before_validation 回调编写 rspec 测试?
【发布时间】:2014-02-10 02:07:07
【问题描述】:

我有一个模型,它使用 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 回调时遇到了麻烦,因此我们将不胜感激。

【问题讨论】:

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


    【解决方案1】:

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

    validates_presence_of :call_time
    

    到您的模型,以触发验证

    目前您只执行 set_call_time 方法。不多不少!

    【讨论】:

      猜你喜欢
      • 2013-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多