加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – rspec – 如何与期望中的实际DateTime进行比较?

发布时间:2020-12-17 03:48:25 所属栏目:百科 来源:网络整理
导读:我的rspec: it "can show the current month name" do expect(Calendar.create_date_using_month(1)).to eq '2000-01-01 00:00:00 -0500'end 失败了: expected: "2000-01-01 00:00:00 -0500" got: 2000-01-01 00:00:00 -0500 对于我的代码: def self.crea
我的rspec:

it "can show the current month name" do
  expect(Calendar.create_date_using_month(1)).to eq '2000-01-01 00:00:00 -0500'
end

失败了:

expected: "2000-01-01 00:00:00 -0500"
     got: 2000-01-01 00:00:00 -0500

对于我的代码:

def self.create_date_using_month(n)
  Time.new(2000,n,1)
end

我应该/可以更改RSpec,以便我与实际字符串而不是日期进行比较吗?

我试过:Date.strptime(“{2000,1,1}”,“{%Y,%m,%d}”)

但这给了我

expected: #<Date: 2000-01-01 ((2451545j,0s,0n),+0s,2299161j)>
        got: 2000-01-01 00:00:00 -0500

解决方法

我对你在这里测试的内容感到有点困惑.如果create_data_using_month创建Time对象,则应将其与Time对象进行比较.

这条信息:

expected: "2000-01-01 00:00:00 -0500"
     got: 2000-01-01 00:00:00 -0500

告诉你它期望带有日期的文字字符串,但得到了一个to_s恰好相同的对象.

所以我想你可以通过改变它来“修复”它:

it "can show the current month name" do
  expect(Calendar.create_date_using_month(1).to_s).to eq '2000-01-01 00:00:00 -0500'
end

但这看起来很奇怪,那是你想要的吗?如果在具有不同时区设置的计算机上进行测试,也可能会出现问题.

我只是这样做:

it "can show the current month name" do
  expect(Calendar.create_date_using_month(1)).to eq Time.new(2000,1)
end

这对我来说很好.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读