我遇到的问题是在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
RSpec的:
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