【发布时间】:2014-04-06 13:39:32
【问题描述】:
我第一次使用验证,我正在尝试验证一个 amount_spent 和一个 no_of_purchases 字段,以便它只接受整数而不是字符串。所以 200 是有效的,但“两百”不是。但是,当我尝试进行此测试时,字符串部分失败,但我不确定为什么。这是我的 rspec 测试文件的 sn-p:
it 'requires a # of purchases' do
customer = Customer.new(valid_customer.merge(no_of_purchases: ''))
customer_2 = Customer.new(valid_customer.merge(no_of_purchases: 0))
customer_3 = Customer.new(valid_customer.merge(no_of_purchases: 'twenty'))
expect(customer).to_not be_valid
expect(customer.errors[:no_of_purchases]).to include "can't be blank"
expect(customer_2).to be_valid
expect(customer_3).to_not be_valid
expect(customer_3.errors[:no_of_purchases]).to include "is not a number"
end
it 'requires an amount spent' do
customer = Customer.new(valid_customer.merge(amount_spent: ''))
customer_2 = Customer.new(valid_customer.merge(no_of_purchases: 0))
customer_3 = Customer.new(valid_customer.merge(no_of_purchases: 'twenty'))
expect(customer).to_not be_valid
expect(customer.errors[:amount_spent]).to include "can't be blank"
expect(customer_2).to be_valid
expect(customer_3).to_not be_valid
expect(customer_3.errors[:no_of_purchases]).to include "is not a number"
end
这是我的模型文件:
validates_presence_of :first_name
validates_presence_of :last_name
validates_presence_of :email
validates_presence_of :no_of_purchases, numericality: true
validates_presence_of :amount_spent, numericality: true
我没有看到错误。我已经指定数值为真,所以它不应该验证字符串。唯一可能是问题是我在我的模式文件中放置了一个默认值 0。我很确定这是问题所在,因为当我使用 binding.pry 时,客户 3 的 no_of_purchase,amount_spent 为 0 而不是“二十”。
问题 1:为什么要这样做? 问题 2:如何解决?
感谢您的帮助。
【问题讨论】:
标签: ruby-on-rails validation rspec