2

shoulda を使用して、このテストを行うときに空白を許可する方法についてのアイデア:

should validate_uniqueness_of(:email)

ありがとう。

4

3 に答える 3

3

私はそれを理解しました!! validate_uniqueness_of は、データベースの最初のレコードで現在テストしている属性の値に依存します。したがって、データベースの最初のレコードがその属性に対してたまたま空白または nul である場合、テストは常に次のようなエラーを返します。 customer_number が nil に設定されている場合、"has already been taken" を含むエラーが予想されますが、エラーはありません。

では、これを修正するにはどうすればよいでしょうか。既存のすべてのレコードを削除し、最初のレコードに属性の値が入力されていることを確認してください。

モデル:

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

これで一部の人々の問題が解決されることを願っています:)

于 2011-11-09T19:03:35.303 に答える
2
should allow_value(" ").for(:email)
should allow_value(nil).for(:email)
于 2010-06-17T13:17:35.710 に答える
-3

多分

should validate_uniqueness_of(:email, :allow_blank => true)
于 2010-08-19T18:02:01.917 に答える