Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails RSpec-日期应介于两个日期之间_Ruby On Rails_Ruby_Rspec - Fatal编程技术网

Ruby on rails RSpec-日期应介于两个日期之间

Ruby on rails RSpec-日期应介于两个日期之间,ruby-on-rails,ruby,rspec,Ruby On Rails,Ruby,Rspec,如何测试一个日期以确定它是否在两个日期之间?我知道我可以做两个大于和小于的比较,但我想要一个RSpec方法来检查日期的“中间性” 例如: it "is between the time range" do expect(Date.now).to be_between(Date.yesterday, Date.tomorrow) end 我试过了expect(range)。想涵盖(主题),但运气不好。我自己没有试过,但根据你的说法,应该用不同的方法: it "is between the

如何测试一个日期以确定它是否在两个日期之间?我知道我可以做两个大于和小于的比较,但我想要一个RSpec方法来检查日期的“中间性”

例如:

it "is between the time range" do
    expect(Date.now).to be_between(Date.yesterday, Date.tomorrow)
end

我试过了
expect(range)。想涵盖(主题)
,但运气不好。

我自己没有试过,但根据你的说法,应该用不同的方法:

it "is between the time range" do    
  (Date.yesterday..Date.tomorrow).should cover(Date.now)
end

Date.today.应该介于(Date.today-1.day,Date.today+1.day)
您必须定义匹配器,请检查

可能是

RSpec::Matchers.define :be_between do |expected|
  match do |actual|
    actual[:bottom] <= expected && actual[:top] >= expected
  end
end

您编写的两个语法都是正确的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::beday
Date::tomory
。您需要手动调整它:

it 'is between the time range' do
  expect(Date.today).to be_between(Date.today - 1, Date.today + 1)
end
由于RSpec的内置,第一个版本可以正常工作。该匹配器了解对象上定义的方法,并将它们以及可能的
版本委托给它们。对于
Date
,谓词来自include
compariable
(参见链接)


第二个版本之所以有效,是因为RSpec定义了matcher。

我在问题中指出,我已经尝试过了,但运气不佳。我猜你错过了。哦,对了,我想
期望
应该
之间是有区别的。道歉。看看@spullen的答案,差别不大。虽然这个解决方案可能有效,但我不太喜欢它如何与日期/时间进行比较。这很好用。我很惊讶我找不到它的任何文档。甚至不需要定义它。更喜欢
在(1.day)之内。of(Date.today)
。这是一个很好的解决方案,但似乎RSpec已经定义好了(根据我的应用程序)。
it 'is between the time range' do
  expect(Date.today).to be_between(Date.today - 1, Date.today + 1)
end