Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RSpec - Date should be between two dates

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.

like image 951
Artem Kalinchuk Avatar asked Jun 19 '13 19:06

Artem Kalinchuk


4 Answers

Date.today.should be_between(Date.today - 1.day, Date.today + 1.day)

like image 95
spullen Avatar answered Oct 25 '22 22:10

spullen


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.

like image 39
Aaron K Avatar answered Oct 25 '22 21:10

Aaron K


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
like image 37
Amir Avatar answered Oct 25 '22 22:10

Amir


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
like image 31
soyellupi Avatar answered Oct 25 '22 22:10

soyellupi