Trouble comparing time with RSpec

后端 未结 7 744
北荒
北荒 2020-12-12 15:23

I am using Ruby on Rails 4 and the rspec-rails gem 2.14. For a my object I would like to compare the current time with the updated_at object attribute after a c

7条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-12 15:45

    The easiest way I found around this problem is to create a current_time test helper method like so:

    module SpecHelpers
      # Database time rounds to the nearest millisecond, so for comparison its
      # easiest to use this method instead
      def current_time
        Time.zone.now.change(usec: 0)
      end
    end
    
    RSpec.configure do |config|
      config.include SpecHelpers
    end
    

    Now the time is always rounded to the nearest millisecond to comparisons are straightforward:

    it "updates updated_at attribute" do
      Timecop.freeze(current_time)
    
      patch :update
      @article.reload
      expect(@article.updated_at).to eq(current_time)
    end
    

提交回复
热议问题