2016-08-11 91 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

相关问题