2011-12-21 56 views
0

我试图阻止保存记录,如果它有name属性中的空格。我使用的是包含ActiveModel的Mongoid,因此它应该和ActiveRecord完全一样。如何使用ActiveModel格式验证?

class Post 
    include Mongoid::Document 
    field :name, type: String 

    validates :name, presence: true, format: { :with => /\S/ } 
end 

这是我的规格。最后一个失败,我不明白为什么。

describe Post do 
    describe "validations" do 
    # passes 
    it "should require a name" do 
     post = Post.new name: nil 
     post.should_not be_valid 
    end 

    # passes 
    it "should accept valid names" do 
     post = Post.new name: "hello-with-no-spaces" 
     post.should be_valid 
    end 

    # fails ????? 
    it "should reject invalid names" do 
     post = Post.new name: "hello with spaces" 
     post.should_not be_valid 
    end 
    end 
end 

回答

3

我想你只想在你的名字字段中输入字符。所以你应该使用:

validates :name, presence: true, format: { :with => /^\S+$/ } 

查看结果here。此外,您还可以使用invalid,使您的测试更流畅,像在以下几点:

post.should be_invalid 

顺便说一句,这是一个品味的问题。

+0

是的,工作。我可以用'be_valid'和'invalid'两种方法。反正很高兴认识。谢谢。 – 2011-12-21 14:07:10