【问题标题】:Allow blank on should validate_uniqueness_of在 validate_uniqueness_of 上允许空白
【发布时间】:2010-06-15 20:01:20
【问题描述】:

使用应该,任何想法如何在进行此测试时允许空白:

should validate_uniqueness_of(:email)

谢谢。

【问题讨论】:

    标签: ruby-on-rails testing shoulda


    【解决方案1】:

    我想通了!! validate_uniqueness_of 依赖于您当前在数据库中的第一条记录上测试的属性的值。因此,如果数据库中的第一条记录恰好是该属性的空白或 nul,您的测试将始终给出如下错误:“Failure/Error: it { should validate_uniqueness_of(:customer_number).case_insensitive.scoped_to(:user_id) }当 customer_number 设置为 nil 时,预期的错误将包括“已经采取”,没有错误”。

    那么我们该如何解决这个问题呢?确保删除所有现有记录,并且第一条记录包含属性的填充值。

    型号:

    validates_uniqueness_of :customer_number, :scope => :user_id, :case_sensitive => false, :allow_blank => true, :allow_nil => true
    

    型号规格:

    describe 'Validation' do
    
      it { should allow_value('').for(:customer_number) }
    
      describe 'When a user exists with the same customer_number and user' do
        before(:each) do 
          Customer.destroy_all
          # Saving a single customer to validate uniqueness.
          @existing = Factory(:customer, :customer_number => 'test') # If you leave customer_number blank here the matcher will check if it can save a new record with a blank customer_number which is possible since we allow blanks. So make sure your first record has a filled in value!!
        end
    
        subject do
          Factory.build(:customer)
        end
    
        it { should validate_uniqueness_of(:customer_number).case_insensitive.scoped_to(:user_id) }
      end
    end
    

    希望这能解决一些人的问题:)

    【讨论】:

    • 这是对这次测试失败的最好解释(这似乎是一个很常见的问题!)。谢谢。
    【解决方案2】:
    should allow_value(" ").for(:email)
    should allow_value(nil).for(:email)
    

    【讨论】:

    • 当电子邮件设置为 nil 时,我仍然会收到“预期的错误,包括“已被使用”,运行时没有错误”应该 validate_uniqueness_of(:email)。
    【解决方案3】:

    也许

    should validate_uniqueness_of(:email, :allow_blank => true)
    

    【讨论】:

      猜你喜欢
      • 2013-01-19
      • 2010-10-22
      • 1970-01-01
      • 2012-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-31
      • 1970-01-01
      相关资源
      最近更新 更多