2011-12-21 54 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