【问题标题】:how to verify length and numericality of an atribute in rails with Rspec如何使用 Rspec 验证 Rails 中属性的长度和数值
【发布时间】: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。有什么更好的方法来测试或实现它?

【问题讨论】:

标签: ruby-on-rails ruby rspec shoulda


【解决方案1】:

这可能是因为format_phone_number 回调仅在验证之前触发。虽然我没有使用 Fabrication gem,the documentation 表示它初始化 ActiveRecord 对象但不调用 savevalid?。因此不会触发before_validation 回调。尝试在 rspec 断言之前添加valid?

it "should remove non-numeric characters" do
  bob = Fabricate(:customer, first_name: "Bob", last_name: "Smith", phone_number: "555-777-8888" )
  bob.valid?
  expect(bob.phone_number).to eq('5557778888')
end

或者,您可以使用 after_initialize ActiveRecord callback 在构建 Customer 对象后立即触发格式化:

class Customer < ActiveRecord::Base
  #...
  after_initialize :format_phone_number

  #...
end

【讨论】:

猜你喜欢
  • 2022-01-27
  • 1970-01-01
  • 2012-10-18
  • 2015-07-04
  • 1970-01-01
  • 1970-01-01
  • 2013-12-21
  • 2014-02-20
  • 1970-01-01
相关资源
最近更新 更多