允许空白应该validate_uniqueness_of

时间:2010-06-15 20:01:20

标签: ruby-on-rails testing shoulda

使用shoulda,任何想法如何在进行此测试时留空:

should validate_uniqueness_of(:email)

感谢。

3 个答案:

答案 0 :(得分:2)

should allow_value(" ").for(:email)
should allow_value(nil).for(:email)

答案 1 :(得分:2)

我已经弄明白了!! validate_uniqueness_of依赖于您当前在数据库中的第一条记录上测试的属性的值。因此,如果数据库中的第一条记录对于该属性恰好是空白或为零,则测试将始终给出如下错误:“失败/错误:它{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 :(得分:-3)

也许

should validate_uniqueness_of(:email, :allow_blank => true)
相关问题