1

我正在为具有以下约束的录音建立一个模型

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 来确定。我真的很困惑为什么这会失败。

编辑:

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

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

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

4

1 回答 1

0

尝试:

PHONE_FORMAT = /^([0-9]+|Unavailable)$/
于 2013-02-13T21:23:36.343 回答