【发布时间】:2014-11-06 22:30:07
【问题描述】:
我有一个包含名字、姓氏和电话号码的客户模型。我想让用户以任何格式输入电话号码,例如 555-555-5555 或 (555)555-5555 或 555.555.5555
这是我的客户模型
class Customer < ActiveRecord::Base
before_validation(on: :create) { format_phone_number }
validates_presence_of :first_name, :last_name, :phone_number
validates :phone_number, numericality: true, length: {minimum: 10}
private
def format_phone_number
self.phone_number = phone_number.gsub(/[^0-9]/, "") if attribute_present?("phone_number")
end
end
format_phone_number 方法在验证之前会去除所有非数字字符,然后我想验证它的长度是否为 10
这是我的规格
describe Customer do
it { should validate_presence_of(:first_name)}
it { should validate_presence_of(:last_name)}
it { should validate_presence_of(:phone_number)}
it { should ensure_length_of(:phone_number).is_at_least(10) }
describe "phone_number" do
it "should remove non-numeric characters" do
bob = Fabricate(:customer, first_name: "Bob", last_name: "Smith", phone_number: "555-777-8888" )
expect(bob.phone_number).to eq('5557778888')
end
end
end
当我运行它时,我得到了这个错误
Failure/Error: it { should ensure_length_of(:phone_number).is_at_least(10) }
Did not expect errors to include "is too short (minimum is 10 characters)" when phone_number is set to "xxxxxxxxxx", got error: is too short (minimum is 10 characters)
所以看起来 Rspec 正在尝试使用 "xxxxxxxxxx" 测试长度,而我的方法是在对象保存之前剥离所有 x。有什么更好的方法来测试或实现它?
【问题讨论】:
-
stackoverflow.com/q/10848748/128421 会是很好的阅读材料。
标签: ruby-on-rails ruby rspec shoulda