如何测试日期以查看它是否在两个日期之间?我知道我可以进行两次大于和小于比较,但我想要一个 RSpec 方法来检查日期的“中间值”。
例如:
it "is between the time range" do
expect(Date.now).to be_between(Date.yesterday, Date.tomorrow)
end
我试过expect(range).to cover(subject)
但没有运气。
如何测试日期以查看它是否在两个日期之间?我知道我可以进行两次大于和小于比较,但我想要一个 RSpec 方法来检查日期的“中间值”。
例如:
it "is between the time range" do
expect(Date.now).to be_between(Date.yesterday, Date.tomorrow)
end
我试过expect(range).to cover(subject)
但没有运气。
Date.today.should be_between(Date.today - 1.day, Date.today + 1.day)
您编写的两种语法都是正确的 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 的内置谓词匹配器,第一个版本有效。这个匹配器理解在对象上定义的方法,并委托给它们以及可能的?
版本。对于Date
,谓词Date#between?
来自包括Comparable
(见链接)。
第二个版本有效,因为 RSpec 定义了覆盖匹配器。
我自己没有尝试过,但根据这个你应该使用它有点不同:
it "is between the time range" do
(Date.yesterday..Date.tomorrow).should cover(Date.now)
end
你必须定义一个匹配器,检查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