使用更改匹配器时如何处理TimeWithZone类

时间:2015-03-04 01:44:42

标签: ruby-on-rails ruby rspec

我有这样的方法:

class Company < ActiveRecord::Base
  before_save :update_read_status  
  def update_read_status
    if read_changed?
      column = read ? :read_at : :unread_at
      self[column] = Time.zone.now
    end
  end
end

我想用这个RSpec测试代码:

  context "#update_read_status" do
  before{ company.update_attributes(read_at: 2.months.ago) }
    context "when read become true" do
      it "read_at be current time" do
        expect{ company.update_attributes(read: true) }.to change{ company.read_at }.from(2.months.ago).to(Time.current)
      end
    end
  end

我知道这个规范失败了,因为测试期间时间正在改变,但我怎样才能将时间与change匹配器进行比较?

我发现了一个类似的问题Trouble comparing time with RSpec,但在我的情况下,使用to_s方法或be_within匹配器的方式不可用。

1 个答案:

答案 0 :(得分:0)

使用to_i方法从Epoch开始以秒为单位获取时间,并使用这些秒作为参数以Time.at构建新时间。这将忽略那些搞乱测试的毫秒。

expect{ company.update_attributes(read: true) }
.to change{ Time.at(company.read_at.to_i) }
.from(2.months.ago).to(Time.at(Time.current.to_i))
相关问题