daveasdf_2
daveasdf_2

Reputation: 81

TimeCop not adjusting time in model method

Using Rails, Rspec, FactoryBot, Capybara, Whenever, TimeCop.

I'm trying to trigger a modal method at '00:01, every 1.day' (12:01am daily) during an Rspec/Capybara test, in order to test the code that is triggered in the Cron. I'm trying TimeCop to travel back to 00:00:30 of the current day in order to trigger the cron scheduled for 00:01.

Essentially I need to figure out how to fire cron on cue in test environment, so I can test the code that the various cron jobs initiates. Some cron are scheduled for once a day, some once a month etc., so I was hoping to set up TimeCop to travel to the right time, slightly before the Cron is scheduled, so I can start the cron job and test the code in Rspec.

Rspec (set TimeCop time to 12:01 am of current day):

let (:time_travel) do
  new_time = Time.local(Time.new.year, Time.new.month, Time.new.day, 0, 0, 30)
  Timecop.travel(new_time)
end

Problem is, the cron is not firing the cron that is scheduled for 00:01, and I assume it is because the modal method is being interpreted at runtime, before TimeCop travels through time, because if I run the cron every 1.minute, and put this in the modal method:

Modal method code:

def self.transfer_to_host
    puts "1 ========#{Time.now} --- Time.now (local)"
    puts "2 ========#{Time.now.utc} --- Time.now (utc)"

The cron_log.log shows my machine's local time (not TimeCop time):

1 ========2023-10-26 10:00:06 -0400 --- Time.now (local)
2 ========2023-10-26 14:00:06 UTC --- Time.now (utc)

But while if I binding.pry in the Rspec, it shows theTimeCop time:

[1] pry(#<RSpec::ExampleGroups::HPETRANSFER>)> Time.now
=> 2023-10-26 00:00:47 -0400

How do I get TimeCop to reach schedule.rb and HostPublicEvent.transfer_to_host, so that they fire at 00:01?

Schedule.rb (whenever)

every 1.day, :at => '00:01' do
  runner "HostPublicEvent.transfer_to_host", :environment => 'test'
end

Rspec:

describe "HPE TRANSFER ", type: :system do

  let (:time_travel) do
   new_time = Time.local(Time.new.year, Time.new.month, Time.new.day, 0, 0, 30)
   Timecop.travel(new_time)
  end

  ....
  scenario "MONEY TRANSFER TO HOST AFTER A WEEK", :js => true do

    ...
    ...
    time_travel

    visit root_path

    sleep 1
    click_on "I agree"
    binding.pry

I'm not sure how to get TimeCop to adjust time in model method.

Upvotes: 0

Views: 153

Answers (0)

Related Questions