Dex
Dex

Reputation: 12759

Why does strptime behave differently in Rails' test environment?

I'm trying to parse the date 2/31/2019, which should raise an error.

In the Rails console this works as expected in development mode, but my tests are failing in test mode because it returns March 3, 2019.

Date.strptime("2/31/2019", "%m/%d/%Y") #=> dev env: error
Date.strptime("2/31/2019", "%m/%d/%Y") #=> test env: “Sun, 03 Mar 2019”

The commands I'm using are:

rails c
RAILS_ENV=test rails c
rspec <filename>

I'm using Ruby 2.3.1 and Rails 5.0.6.

Upvotes: 1

Views: 86

Answers (1)

Marek Lipka
Marek Lipka

Reputation: 51171

Timecop overwrites the Date.strptime definition:

[4] pry(main)> puts Date.method(:strptime).source
def strptime_with_mock_date(str = '-4712-01-01', fmt = '%F', start = Date::ITALY)
  unless start == Date::ITALY
    raise ArgumentError, "Timecop's #{self}::#{__method__} only " +
      "supports Date::ITALY for the start argument."
  end

  Time.strptime(str, fmt).to_date
end

That's why the output is different between environments, since Timecop is only required in test.

Upvotes: 2

Related Questions