如何测试日期以查看它是否在两个日期之间?我知道我可以进行两次大于和小于比较,但我想要一种RSpec方法来检查日期的“好坏”。
例如:
it "is between the time range" do
expect(Date.now).to be_between(Date.yesterday, Date.tomorrow)
end
我试过expect(range).to cover(subject)
但没有运气。
答案 0 :(得分:23)
Date.today.should be_between(Date.today - 1.day, Date.today + 1.day)
答案 1 :(得分:10)
您编写的两种语法都是正确的RSpec:
it 'is between the time range' do
expect(Date.today).to be_between(Date.yesterday, Date.tomorrow)
end
it 'is between the time range' do
expect(Date.yesterday..Date.tomorrow).to cover Date.today
end
如果您不使用Rails,则不会定义Date::yesterday
或Date::tomorrow
。您需要手动调整它:
it 'is between the time range' do
expect(Date.today).to be_between(Date.today - 1, Date.today + 1)
end
第一个版本的工作原因是RSpec内置predicate matcher。此匹配器了解在对象上定义的方法,并委托它们以及可能的?
版本。对于Date
,谓词Date#between?
来自Comparable
(见链接)。
第二个版本有效,因为RSpec定义了cover匹配器。
答案 2 :(得分:2)
我自己没有尝试过,但根据this,您应该稍微使用它:
it "is between the time range" do
(Date.yesterday..Date.tomorrow).should cover(Date.now)
end
答案 3 :(得分:1)
您必须定义匹配器,请检查https://github.com/dchelimsky/rspec/wiki/Custom-Matchers
可能是
RSpec::Matchers.define :be_between do |expected|
match do |actual|
actual[:bottom] <= expected && actual[:top] >= expected
end
end
它允许你
it "is between the time range" do
expect(Date.now).to be_between(:bottom => Date.yesterday, :top => Date.tomorrow)
end