2010-06-15 50 views

回答

2
should allow_value(" ").for(:email) 
should allow_value(nil).for(:email) 
+0

我仍然得到“预期的错误,包括 “已被占用” 的时候电子邮件设置为零,没有错误“在运行时应validate_uniqueness_of(:电子邮件)。 – Pablo 2010-06-18 09:41:52

-3

也许

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

不,那不行。 – Pablo 2010-09-24 19:44:28

2

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

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

型号:

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 

希望这澄清了一些人的问题:)

+0

这是此测试失败的最佳解释(这似乎是一个相当常见的问题!)。谢谢。 – 2016-03-03 03:12:48