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