0

我在强制字段不为 nil 时遇到问题ActiveAttr::Model

是否有一种优雅的方式在模型中强制执行此约束,而不是在控制器中定义它?还是我对场景的测试不正确?

模型:

class Message
  include ActiveAttr::Model

  attribute :name, :presence => true, :allow_nil => false, :allow_blank => false
  attribute :email, :presence => true
  attribute :content, :presence => true

  validates_format_of :email, :with => /^[-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}$/i
  validates_length_of :content, :maximum => 500
end

规格:

module MessageSpecHelper
  def valid_message_attributes
    {
       :name => "Walter White",
       :email => "walter@hailtheking.com",
       :content => "I am the one who knocks"
   }
  end
end

it "should have error on name (alternate with nil)" do 
  @message.attributes = valid_message_attributes.except(:name => nil)
  @message.should have(1).error_on(:name)
end
4

0 回答 0