1
我设置了一个模型记录有以下限制Rails的模型没有格式验证,正则表达式
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...
,最终对我来说很有意义,到一个点。是所有事情都变得混乱的原因(错误返回真实,反之亦然),因为一旦属性使记录无效,我不能再改变它了吗?看来是这样,我只是想确定一下。
由于没有斜杠?我需要任何类型的报价吗? – 2013-02-13 22:47:50
我补充说,与正斜杠和得到了与以前相同的错误 – 2013-02-14 01:08:17
@BradRice叶这是一个错字,应该是斜杠(固定)。我似乎无法复制你所得到的错误...... – veritas1 2013-02-14 11:41:09