Artem Kalinchuk
Artem Kalinchuk

Reputation: 6652

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.

Upvotes: 19

Views: 10540

Answers (4)

Aaron K
Aaron K

Reputation: 6961

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.

Upvotes: 12

soyellupi
soyellupi

Reputation: 95

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

Upvotes: 1

spullen
spullen

Reputation: 3317

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

Upvotes: 29

Amir
Amir

Reputation: 1872

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

Upvotes: 2

Related Questions