Last active
November 23, 2019 09:56
-
-
Save madogiwa0124/19f5099f64e967d1bba9ddd5f6bd5916 to your computer and use it in GitHub Desktop.
rspecを使ったfeature specでjavascriptの時間を指定時間に固定するhelper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# === sample === | |
# require 'rails_helper' | |
# require 'helpers/travel_to_javascript' | |
# RSpec.feature 'sample', type: :feature do | |
# it 'sample expect' do | |
# travel_to_javascript(page, "2010/11/11 12:00".in_time_zone) do | |
# page.execute_script("console.error('now1:', new Date())") | |
# page.execute_script("console.error('now2:', Date.now())") | |
# pp page.driver.browser.manage.logs.get(:browser).map(&:message) | |
# # => ["console-api 0:32 \"now1:\" Thu Nov 11 2010 12:00:00 GMT+0900 (日本標準時)", | |
# # "console-api 0:32 \"now2:\" 1289444400000"] | |
# end | |
# page.execute_script("console.error('now1:', new Date())") | |
# page.execute_script("console.error('now2:', Date.now())") | |
# pp page.driver.browser.manage.logs.get(:browser).map(&:message) | |
# # => ["console-api 0:32 \"now1:\" Sat Nov 23 2019 18:45:37 GMT+0900 (日本標準時)", | |
# # "console-api 0:32 \"now2:\" 1574502337831"] | |
# end | |
# end | |
module TravelToJavascript | |
def travel_to_javascript(page, datetime) | |
page.execute_script time_stop_javascript(datetime) | |
yield | |
page.execute_script time_undo_javsctipt | |
end | |
private | |
def time_stop_javascript(rb_datetime) | |
<<~JS | |
originDate = Date; | |
Date = #{time_stop_js_function_for_date(rb_datetime)}; | |
Date.now = #{time_stop_js_function_for_date_now(rb_datetime)}; | |
JS | |
end | |
def time_undo_javsctipt | |
'Date = originDate;' | |
end | |
def time_stop_js_function_for_date(rb_datetime) | |
<<~JS | |
function (datetime) { | |
if (datetime) { | |
return new originDate(datetime); | |
} else { | |
return new originDate("#{rb_datetime.iso8601}"); | |
} | |
} | |
JS | |
end | |
def time_stop_js_function_for_date_now(rb_datetime) | |
<<~JS | |
function (datetime) { | |
if (datetime) { | |
return new originDate(datetime).getTime(); | |
} else { | |
return new originDate("#{rb_datetime.iso8601}").getTime(); | |
} | |
} | |
JS | |
end | |
end | |
RSpec.configure do |config| | |
config.include(TravelToJavascript, :type => :feature) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment