Rails模型失败格式验证,正则表达式

时间:2013-02-13 20:34:23

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

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

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...

最终对我有意义。原因是一切都搞砸了(falses返回true,反之亦然)因为一旦属性使记录无效,我再也无法改变它?看来情况确实如此,我只是想确定一下。

1 个答案:

答案 0 :(得分:0)

尝试:

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