测试存在:Rails中的真实验证

时间:2012-06-18 12:16:43

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

在我的持有人测试文件中:

 test "name must be present" do
  holder = Holder.new(name: "name")
  assert holder.valid?
 end

 test "name must not be blank" do
  h = Holder.new(name: "    ")
  assert !h.valid?
 end

 test "name must not be nil" do
  h = Holder.new(name: nil)
  assert !h.valid?
 end

我的持有人模型看起来像:

class Holder < ActiveRecord::Base
  attr_accessible :description, :name, :user_id

  validates_length_of :name, maximum: 75
  validates_length_of :description, maximum: 250

  validate :name, presence: true
end

但是,当我运行测试时,最后两次验证仍然是红色的。我需要做些什么来测试它们才能变绿?

1 个答案:

答案 0 :(得分:3)

您忘记了s中的validate。它必须是:

validates :name, presence: true

validatevalidates是完全不同的方法。

请参阅:http://api.rubyonrails.org/classes/ActiveModel/Validations/ClassMethods.html