【问题标题】:How do I use ActiveModel format validations?如何使用 ActiveModel 格式验证?
【发布时间】:2011-12-21 13:30:33
【问题描述】:

如果name 属性中有空格,我会尝试阻止保存记录。我正在使用包含 ActiveModel 的 Mongoid,因此它应该与 ActiveRecord 完全相同。

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

【问题讨论】:

    标签: ruby-on-rails regex ruby-on-rails-3 mongoid activemodel


    【解决方案1】:

    我认为您只需要名称字段中的字符。所以你应该使用:

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

    查看结果here。此外,您可以使用invalid 使您的测试更加流畅,如下所示:

    post.should be_invalid
    

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

    【讨论】:

    • 是的,有效。我可以在 be_validinvalid 的事情上采取任何一种方式。无论如何很高兴知道。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-21
    • 2018-10-06
    • 1970-01-01
    • 2016-10-02
    • 1970-01-01
    • 2013-04-04
    相关资源
    最近更新 更多