2016-07-14 30 views
0

我驗證日期字段如下:如何使用早該匹配器來測試日期驗證

驗證:RETURN_DATE,包含:{在:(Date.today + 1.day..Date.today + 4.weeks )}

我測試它使用Rspec的語法如下:

it "should only accept return date that is later than the current date" do 
    quotation_request = FactoryGirl.build(:quotation_request, return_date: Date.today) 
    expect(quotation_request.valid?).to be_falsy 
end 

在報價請求模型驗證:

validates :return_date, inclusion: {in:(Date.today+1.day..Date.today+4.weeks) 

這可以工作。我想知道是否有一種方法可以使用Shoulda匹配器來測試,如果有的話,以及如何做到這一點?

回答

0

首先,你應該使用一個進程的日期

validates :return_date, inclusion: { in: ->(model) { (Date.today+1.day)..(Date.today+4.weeks) } } 

然後馮·可以調整到某一領域的評估,看看當它是假的,真正的

# Set the expectation that the factory is setup correctly 
expect(quotation_request).to be_valid 

# Then check that values "just" out of range make it invalid 
quotation_request.return_date = Date.today 
expect(quotation_request).not_to be_valid 

quotation_request.return_date = Date.today+4.weeks+1.day 
expect(quotation_request).not_to be_valid 
+0

我增加了驗證我使用的日期,使我測試更清晰 – chell

+0

我已經更新了答案,包括更好的描述如何解決您遇到的問題@chell – nort

+0

感謝Nort。我試圖使用proc,但它會產生錯誤的參數數量錯誤(1代表0)。這不是建立在Rails日期的工作與proc一樣嗎? – chell