使用应该,任何想法如何在进行此测试时允许空白:
should validate_uniqueness_of(:email)
谢谢。
我已经想通了!!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
希望这能解决一些人的问题:)
should allow_value(" ").for(:email)
should allow_value(nil).for(:email)
也许
should validate_uniqueness_of(:email, :allow_blank => true)