【问题标题】:Rails model fails format validation, regexRails 模型格式验证失败,正则表达式
【发布时间】:2013-02-13 20:34:23
【问题描述】:

我正在为具有以下约束的录音设置模型

class Recording < ActiveRecord::Base
  attr_accessible :agent_id, :confirmation, :filepath, :phone, :call_queue_id, :date
  belongs_to :call_queue

  PHONE_FORMAT = /^[0-9]+$|Unavailable/

  validates_presence_of :call_queue_id, :agent_id, :phone, :filepath, :date
  validates :phone, format: { with: PHONE_FORMAT }
end

并尝试使用以下规范对其进行测试

describe Recording do
  let(:queue) { FactoryGirl.create(:call_queue) }
  before { @recording = queue.recordings.build(FactoryGirl.attributes_for(:recording)) }
  subject { @recording }

  # Stuff omitted...

  describe "phone" do
    it "should be present" do
      @recording.phone = ''
      @recording.should_not be_valid
    end

    context "with a valid format" do
      it "should only consist of digits" do
        @recording.phone = 'ab4k5s'
        @recording.should_not be_valid
      end

      it "should only match 'Unavailable'" do
        @recording.phone = 'Unavailable'
        @recording.should be_valid
      end
    end
  end  
end

前两个测试通过,但第三个测试失败,结果如下:

Failure/Error: @recording.should be_valid
   expected valid? to return true, got false

我用rubular 测试了我的正则表达式以确保它正常工作,然后再次使用 irb 以确保它。我真的很困惑为什么会失败。

编辑:

我最终通过更改我在 rspec 中的 before 声明使规范通过:

describe Recording do
  let(:queue) { FactoryGirl.create(:call_queue) }
  before(:each) { @recording = queue.recordings.create(FactoryGirl.attributes_for(:recording) }
  # the rest is the same...

在某种程度上,这最终对我来说是有意义的。一切都变得混乱的原因(假返回真,反之亦然)是因为一旦属性使记录无效,我就不能再改变它了吗?好像是这样,我只是想确定一下。

【问题讨论】:

    标签: ruby-on-rails regex model rspec tdd


    【解决方案1】:

    尝试:

    PHONE_FORMAT = /^([0-9]+|Unavailable)$/
    

    【讨论】:

    • 没有正斜杠?我需要任何形式的报价吗?
    • 我用正斜杠添加了它,得到了和以前一样的错误
    • @BradRice Yeh 这是一个错字,应该是斜线(已修复)。我似乎无法复制您遇到的错误...
    猜你喜欢
    • 2012-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-30
    • 2023-03-28
    • 1970-01-01
    • 2021-05-20
    相关资源
    最近更新 更多