How can I test a date to see if it's between two dates? I know I can do two greater-than and less-than comparisons but I want an RSpec method to check the "betweeness" of the date.
For example:
it "is between the time range" do
expect(Date.now).to be_between(Date.yesterday, Date.tomorrow)
end
I tried expect(range).to cover(subject)
but no luck.
Date.today.should be_between(Date.today - 1.day, Date.today + 1.day)
Both of the syntaxes you wrote are correct 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
If you are not using Rails you won't have Date::yesterday
or Date::tomorrow
defined. You'll need to manually adjust it:
it 'is between the time range' do
expect(Date.today).to be_between(Date.today - 1, Date.today + 1)
end
The first version works due to RSpec's built in predicate matcher. This matcher understand methods being defined on objects, and delegates to them as well as a possible ?
version. For Date
, the predicate Date#between?
comes from including Comparable
(see link).
The second version works because RSpec defines the cover matcher.
I didn't try it myself, but according to this you should use it a bit differently:
it "is between the time range" do
(Date.yesterday..Date.tomorrow).should cover(Date.now)
end
You have to define a matcher, check https://github.com/dchelimsky/rspec/wiki/Custom-Matchers
It could be
RSpec::Matchers.define :be_between do |expected|
match do |actual|
actual[:bottom] <= expected && actual[:top] >= expected
end
end
It allows you
it "is between the time range" do
expect(Date.now).to be_between(:bottom => Date.yesterday, :top => Date.tomorrow)
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With