alert_confirmer.rb 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. module AlertConfirmer
  2. def reject_confirm_from &block
  3. handle_js_modal 'confirm', false, &block
  4. end
  5. def accept_confirm_from &block
  6. handle_js_modal 'confirm', true, &block
  7. end
  8. def accept_alert_from &block
  9. handle_js_modal 'alert', true, &block
  10. end
  11. def get_alert_text_from &block
  12. handle_js_modal 'alert', true, true, &block
  13. get_modal_text 'alert'
  14. end
  15. def get_modal_text(name)
  16. page.evaluate_script "window.#{name}Msg;"
  17. end
  18. private
  19. def handle_js_modal name, return_val, wait_for_call = false, &block
  20. modal_called = "window.#{name}.called"
  21. page.execute_script "
  22. window.original_#{name}_function = window.#{name};
  23. window.#{name} = function(msg) { window.#{name}Msg = msg; window.#{name}.called = true; return #{!!return_val}; };
  24. #{modal_called} = false;
  25. window.#{name}Msg = null;"
  26. block.call
  27. if wait_for_call
  28. timed_out = false
  29. timeout_after = Time.now + Capybara.default_max_wait_time
  30. loop do
  31. if page.evaluate_script(modal_called).nil?
  32. raise 'appears that page has changed since this method has been called, please assert on page before calling this'
  33. end
  34. break if page.evaluate_script(modal_called) ||
  35. (timed_out = Time.now > timeout_after)
  36. sleep 0.001
  37. end
  38. raise "#{name} should have been called" if timed_out
  39. end
  40. ensure
  41. page.execute_script "window.#{name} = window.original_#{name}_function"
  42. end
  43. end