🖥

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

に公開

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

https://github.com/YumaInaura/YumaInaura/issues/2780

チャットメンバー募集

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

https://line.me/ti/g2/eEPltQ6Tzh3pYAZV8JXKZqc7PJ6L0rpm573dcQ

Twitter

https://twitter.com/YumaInaura

公開日時

2019-11-29

Discussion