【问题标题】:rspec expect date to equalrspec 期望日期等于
【发布时间】:2014-09-08 16:55:11
【问题描述】:

我有一个名为工单的对象,它具有以下架构:

# == Schema Information
#
# Table name: work_orders
#
#  id                 :integer          not null, primary key
#  due_on             :date
#  name               :string(255)

我也有对象显示时的Json输出:

{
   id: 1,
   due_on: "2015-06-08",
   name: "my work order"
}

我正在尝试使用 rspec 来确认 json 显示的日期与对象的日期匹配。这是我为其他对象做了 50 次的事情......

我有以下:

exemplar = FactoryGirl.create(:work_order)
...
puts "Test: #{exemplar.due_on}"
expect(exemplar.name).to      eq(hash['name'])   #This works fine!
expect(exemplar.due_on).to    eq(hash['due_on']) #This blows up...

我得到的输出是:

Test: 2015-06-08

expected: "2015-06-08"
     got: Mon, 08 Jun 2015

我不明白“2015 年 6 月 8 日星期一”的来源。当我用 puts 语句打印出日期时,它显示为 2015-06-08...

【问题讨论】:

  • exemplar.due_on 返回2015-06-08?
  • @Stefan 当我使用“puts”时它会这样做,但在“expects”中它给了我“Mon, 08 Jun 2015”

标签: ruby-on-rails ruby json rspec


【解决方案1】:

Rails 将字符串转换为日期对象。 2015-06-08Date#to_s 的输出:

d = Date.today
#=> Thu, 17 Jul 2014

puts d
#=> 2014-07-17

您可以将日期对象与您的字符串进行比较:

expect(exemplar.due_on.to_s).to eq(hash['due_on'])

或:

expect(exemplar.due_on).to eq(Date.parse(hash['due_on']))

或使用Active Support Core Extensions:

expect(exemplar.due_on).to eq(hash['due_on'].to_date)

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-13
  • 1970-01-01
  • 2013-11-26
  • 1970-01-01
相关资源
最近更新 更多