在使用应该匹配器和工厂女孩轨道测试Rails模型验证时遇到问题?



Model:

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

我正在shoulda_matchers一起使用factory_girl_rails。每次我尝试验证我的电子邮件时,我都会收到上述错误。它说电子邮件值为"xx",但工厂电子邮件的长度大于此长度。如何编写将通过的 rspec

应该通过测试错误对象中的消息来测试验证。

除非另行指定,否则 valdation 匹配器仅适用于 rails 默认错误消息:

it { should validate_length_of(:email).with_message("is too short, must be a minimum of 3 characters.") }

with_message方法在此注释中详细介绍。

您理解错误(及其原因(是错误的。该错误说它期望"太短(最少为 3 个字符(",但在错误中它找不到该字符串(rspec 发现"太短,必须至少为 3 个字符",这是您在验证中定义的(。

当你使用应该有匹配器并说

it { should validate_length_of(:email).is_at_least(3) }

我猜它会创建一个电子邮件短于 3 的测试并检查它是否失败,这就是为什么它忽略您的工厂,内部应该 matcher 设置一个固定长度的字符串只是为了让测试通过。

当您在用户中看到错误时,该测试实际上应该有效,因为错误实际上存在,只是字符串不同。因此,您有两种选择:在长度最小时删除自定义消息:3;或者告诉匹配器您期望的消息:

it { should validate_length_of(:email).is_at_least(3).with_message("is too short, must be a minimum of 3 characters.") }

最新更新