- 你好,我真的很困惑如何在 ruby on rails 中使用 rspec 和 shoulda 匹配器测试数据库中的某些字符串。
我去展示我做了什么,结果加上我期待什么。
- 首先,我将 factory_bot_rails 和 shoulda gem 与 rspec 一起使用。
payment_spec.rb
it do
should allow_value('/\A[a-zA-Z]*\z/')
.for(:first_name)
.with_message('first name should contain only letters')
end
工厂/payments.rb
FactoryBot.define do
factory :payment do
first_name { 'Mutebi' }
last_name { 'Godfrey' }
phone_number { '+256780140670' }
address { 'Kampala' }
money_paid { '9.99' }
nin_number { 'NLJ8589654785P' }
created_at { '2023-04-07 12:01:42' }
updated_at { '2023-04-07 12:01:42' }
home_id { 1 }
date { '2023-04-07' }
user_id { '7' }
status { 'pending' }
home
user
end
end
Payment validations is expected to validate that the length of :nin_number is 14
Failure/Error: it { should validate_length_of(:nin_number).is_equal_to(14) }
Expected Payment to validate that the length of :nin_number is 14, but
this could not be proved.
After setting :nin_number to ‹"xxxxxxxxxxxxx"›, the matcher expected
the Payment to be invalid, but it was valid instead.
- 但让我感到困惑的是,即使我没有在模型中添加任何东西来证明它,测试也会通过。如果我添加了应该在 gem 文档中指定的验证,它也会通过。
validates_format_of :first_name,
with: /\A[a-zA-Z]*\z/,
message: 'State must be open or closed'
- 我个人更愿意使用这种在 rails 6 中使用的验证
validates :phone_number, format: { with: /\A\+\d{12}(\d{2})?\z/,
message: 'number should start with +256 with with 12 digits' }