rspecで時間操作をする
今まではtimecop使ってたんだけど、細かい制御までは特にする必要もなかったので ActiveSupport::Testing::TimeHelpers を使ってみる
spec/rails_helper.rbに以下を追記
# This file is copied to spec/ when you run 'rails generate rspec:install' require 'spec_helper' ENV['RAILS_ENV'] ||= 'test' require File.expand_path('../config/environment', __dir__) abort("The Rails environment is running in production mode!") if Rails.env.production? require 'rspec/rails' require 'webdrivers' require 'email_spec' require 'email_spec/rspec' Dir[Rails.root.join('spec', 'support', '**', '*.rb')].sort.each { |f| require f } # Checks for pending migrations and applies them before tests are run. # If you are not using ActiveRecord, you can remove these lines. begin ActiveRecord::Migration.maintain_test_schema! rescue ActiveRecord::PendingMigrationError => e puts e.to_s.strip exit 1 end RSpec.configure do |config| config.use_transactional_fixtures = true config.infer_spec_type_from_file_location! # Filter lines from Rails gems in backtraces. config.filter_rails_from_backtrace! # arbitrary gems may also be filtered via: # config.filter_gems_from_backtrace("gem name") config.include ActiveJob::TestHelper config.include ActiveSupport::Testing::TimeHelpers # <-- 追記 end
使いたい箇所で travel_toで囲む
context "Sample" do it do travel_to('2020-1-1 0:00'.to_time) do # do test end end end
aroundを使って広範囲に反映する
context "Sample" do around do |e| travel_to('2020-1-1 0:00'.to_time) { e.run } end it do # do test end it do # do test end end