如何使用 Shoulda 匹配器来测试日期验证

How to use Shoulda matchers to test date validation

我按如下方式验证日期字段:

验证:return_date,包含:{in:(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 匹配器来测试这个,如果可以的话,是哪个以及如何?

首先,您应该使用 proc 来评估日期

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