LoginSignup
0
0

More than 1 year has passed since last update.

#Rails + rspec + rake タスクで環境変数を利用してタイムゾーンを指定したテストをする例 ( specify local timezone test with rake )

Last updated at Posted at 2019-11-29

rake

namespace :foo do
  task bar: :environment do |task|
    date = if ENV['ON'].present?
             Date.parse(ENV['ON'])
           else
             Time.current.in_time_zone('Tokyo').to_date.yesterday
           end

    Alice.run!(on: date)
  end
end

spec

require "rails_helper"
require "rake"

describe 'foo' do
  before(:all) do
    @rake = Rake::Application.new
    Rake.application = @rake
    Rake.application.rake_require('bar', [Rails.root.join('lib', 'tasks', 'foo')])
    Rake::Task.define_task(:environment)
  end

  before(:each) do
    @rake[task].reenable
  end

  describe  do
    let(:task) { 'foo:bar' }

    context 'when now is beggining of day at JST' do
      before do
        travel_to '2020-01-01 00:00:00'.in_time_zone('Tokyo')
      end

      it do
        expect(Alice).to receive(:run!).with(on: Date.new(2019, 12, 31))
        @rake[task].invoke
      end
    end

    context 'when now is end of day at JST' do
      before do
        travel_to '2020-01-01 23:59:59'.in_time_zone('Tokyo')
      end

      it do
        expect(Alice).to receive(:run!).with(on: Date.new(2019, 12, 31))
        @rake[task].invoke
      end
    end

    context 'when specify target date' do
      before do
        travel_to '2020-01-01 00:00:00'.in_time_zone('Tokyo')
        allow(ENV).to receive(:[]).with('ON').and_return('2020-02-01')
      end

      it do
        expect(Alice).to receive(:run!).with(on: Date.new(2020, 02, 01))
        @rake[task].invoke
      end
    end
  end
end

Original by Github issue

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0