Redirect_to sign in page if AJAX call is not autho

2019-07-31 04:57发布

问题:

I have a form and when you click submit it will make an AJAX call to update the thing you want to change. My user session expires in 4 hours, so if the user wants to update the form and his session has expired in the meantime it will render a flash message asking to reload the page and sign in again.

When trying to test this behavior using Cucumber, Capybara, Selenium and Chrome the AJAX response is never received as the flash message is not rendered. (If I test it manually it works just fine)

I have run another test that renders the flash message when performing another action that also uses AJAX and it succeeds. The difference is that one action renders a view right away and the one that fails redirects to another path and then renders. All controllers inherit from the same BaseController that checks if the user is authorized.

After expiring the session, I call submit form which has these steps:

When /^I submit the form$/ do
  generic_form_page = GenericFormPage.new(Capybara.current_session)
  generic_form_page.submit

  if Capybara.current_session.mode == :poltergeist
    ajax_page = GenericAjaxPage.new Capybara.current_session
    ajax_page.wait_for_ajax_call_to_finish
  else
    Selenium::WebDriver::Wait.new(:timeout => 50)
  end
  sleep 5
end

wait_for_ajax_call_to_finish basically just sleeps for a couple of seconds

This is the action that is failing:

  def update
    @element = Element.find(params[:id])
    if @element.update_attributes(element_params)
      render :json => { :location => another_path(@element.item) }
    else
      render :action => 'edit', :layout => false
    end
  end

The action that is succeeding:

  def edit
    @element = Element.find(params[:id])
    @item = @element.item
    render :layout => false
  end

The AJAX message is this:

handle_ajax_errors = (event, request, settings) ->
  if request.status == 401
    render_flash_error_message("Your session has timed out. Please refresh the page.")
  else
    render_flash_error_message("We're sorry. An error has occurred.")

This is how I am expiring the cookies:

browser = Capybara.current_session.driver.browser
  if browser.respond_to?(:clear_cookies)
    # Rack::MockSession
    browser.clear_cookies
  elsif browser.respond_to?(:manage) and browser.manage.respond_to?(:delete_all_cookies)
    # Selenium::WebDriver
    browser.manage.delete_all_cookies
  else
    raise "Don't know how to clear cookies. Weird driver?"
  end

Thanks!