型号:
validates :email,
uniqueness: {
message: "has been taken."
},
presence: {
message: "cannot be blank."
},
length: {
minimum: 3,
message: "is too short, must be a minimum of 3 characters.",
allow_blank: true
},
format: {
with: /\A[A-Z0-9_\.&%\+\-']+@(?:[A-Z0-9\-]+\.)+(?:[A-Z]{2,13})\z/i,
message: "is invalid.",
if: Proc.new { |u| u.email && u.email.length >= 3 }
}
RSpec:
before(:each) do
@user = FactoryGirl.build(:user)
end
it { should validate_length_of(:email).is_at_least(3) }
错误:
Failure/Error: should validate_length_of(:email).is_at_least(3)
Expected errors to include "is too short (minimum is 3 characters)" when email is set to "xx",
got errors:
* "is too short (minimum is 4 characters)" (attribute: password, value: nil)
* "is too short, must be a minimum of 3 characters." (attribute: email, value: "xx")
* "is not included in the list" (attribute: state, value: "passive")
工厂:
factory :user, class: User do
email FFaker::Internet.email
password FFaker::Internet.password
username FFaker::Internet.user_name
end
我正在将factory_girl_rails与shoulda_matchers一起使用。每次尝试验证电子邮件时,都会不断出现上述错误。它说电子邮件的值为“ xx”,但是工厂电子邮件的长度大于该长度。如何编写将通过的rspec?
答案 0 :(得分:1)
您正在了解错误(及其原因)错误。该错误表明它期望“太短(至少3个字符)”,但在错误中找不到该字符串(rspec发现“太短,必须至少3个字符。”这就是您定义的根据您的验证)。
当使用火锅匹配器并说
时it { should validate_length_of(:email).is_at_least(3) }
我猜想它会创建一个电子邮件短于3的测试,并检查它是否失败,这就是为什么它忽略您的工厂的原因,内部匹配器应该设置固定长度的字符串以使测试通过。
当您看到用户中的错误时,该测试实际上应该可以进行,因为错误实际上在那里,只有字符串不同。因此,您有两个选择:长度最小时删除自定义消息:3;或告诉匹配者您期望什么消息:
it { should validate_length_of(:email).is_at_least(3).with_message("is too short, must be a minimum of 3 characters.") }
答案 1 :(得分:1)
Shoulda-matchers通过测试错误对象中的消息来测试验证。
除非您另外指定,否则valdation匹配器仅适用于rails默认错误消息:
it { should validate_length_of(:email).with_message("is too short, must be a minimum of 3 characters.") }
comment中详细介绍了with_message
方法。