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

How to deal with TimeWithZone class when using change matcher

我有这样的方法:

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 匹配器的方式在我的情况下不可用。

使用 to_i 方法获取自纪元以来的秒数,并使用这些秒数作为参数使用 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))