2016-08-11 32 views
0

Rspec的拋出錯誤:如何獲得適當的電子郵件獨特性的RSpec

1) Client uniqueness validates uniqueness of email 
    Failure/Error: expect(subject).to validate_uniqueness_of :email 

     Client did not properly validate that :email is case-sensitively unique. 
     After taking the given Client, whose :email is 
     ‹"[email protected]"›, and saving it as the existing 
     record, then making a new Client and setting its :email to a different 
     value, ‹"[email protected]"›, the matcher expected the 
     new Client to be valid, but it was invalid instead, producing these 
     validation errors: 

     * pesel: ["This pesel is already in database"] 
     * email: ["This email is already in database"] 

在模型中我已經實現的獨特性和區分大小寫:假電子郵件。

validates :email, presence: true, 
        uniqueness: { case_sensitive: false }, 
        format: { with: VALID_EMAIL_REGEX } 

我也已經實現了方法,即驗證前所有電子郵件都是小寫。

def downcase_email 
    self.email = email.downcase if email.present? 
    end 
before_validation :downcase_email 

爲什麼匹配器會期望新的客戶端有效?它應該是無效的。

subject { FactoryGirl.build(:client) } 
it 'validates uniqueness of email' do 
    expect(subject).to validate_uniqueness_of :email 
end 

客戶端有一個有效的工廠。我試過找到好的解決方案,但是我還沒有找到任何能解決我的問題的方法。

FactoryGirl.define do 
    factory :client do 
    pesel { Faker::Number.number(11) } 
    first_name { Faker::Name.first_name } 
    last_name { Faker::Name.last_name } 
    date_of_birth { Faker::Time.between('1970-01-01', '2000-12-31') } 
    email { Faker::Internet.email } 
    password { Faker::Internet.password } 
    type 'Client' 
    end 
end 

回答

2

FactoryGirl對您的問題在下面的例子中它的文檔後

sequence :email do |n| 
    "person#{n}@example.com" 
    end 

factory :invite do 
    invitee { generate(:email) } 
end 

編輯您的更新:

問題是匹配器validate_uniqueness_of。您也必須爲匹配器調整case_sensitive。所以它應該是validate_uniqueness_of(:email).case_insensitive

+0

我使用faker生成數據。 –

+0

看到我的更新,它是產生錯誤的匹配器。 – slowjack2k

+0

謝謝slowjack2k!現在很棒。祝你今天愉快 :) –

0

檢查,如果你的工廠有弧形托架包裝email屬性類似這樣的:

FactoryGirl.define do 
    factory :client do 
    email { Faker::Internet.email } 
    end 
end 
+0

顯示我的更新後的文章如何看起來像我的客戶端工廠。我寫到客戶有有效的工廠。 –

+1

沒有彎曲支架的工廠仍然有效,但不能保證生成的值的唯一性,工廠不在第一篇文章中,所以我推測這可能是問題所在。道歉。 – fabriciofreitag

相關問題