Help us understand the problem. What is going on with this article?

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

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

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした