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

时间:2016-07-14 09:32:22

标签: rspec-rails ruby-on-rails-4.2 shoulda

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

验证:return_date,included:{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匹配器测试这个以及如果是这样的哪一个以及如何?

1 个答案:

答案 0 :(得分:1)

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

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

然后,yon可以对给定字段进行调整,以查看它何时为假且真实

# 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