Skip to content

Instantly share code, notes, and snippets.

@madogiwa0124
Last active November 23, 2019 09:56
Show Gist options
  • Save madogiwa0124/19f5099f64e967d1bba9ddd5f6bd5916 to your computer and use it in GitHub Desktop.
Save madogiwa0124/19f5099f64e967d1bba9ddd5f6bd5916 to your computer and use it in GitHub Desktop.
rspecを使ったfeature specでjavascriptの時間を指定時間に固定するhelper
# === 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