Monster on Fire

Testing a JavaScript redirect with RSpec

28 June 2017

Last week I worked on an issue that required me to build a JavaScript widget as an unstyled route in our Rails backend app. The JS widget works as follows:

  • user fills in form
  • user input data is passed as url params
  • user is redirected to another site along with the url params

Here are a few things I learnt while building this little feature.

1. Specifying layout for controllers

In the following example, the GenericController will use the layout app/views/layouts/generic.html.erb instead of the app/views/layouts/application.html.erb layout file

class GenericController < ApplicationController
  layout "generic"

Ref: Specifying Layouts for Controllers

2. Testing a redirect

I was able to test a redirect that was triggered in my JS file by setting window.location.href to the value Using RSpec, Capybara (used for feature/acceptance testing) and Poltergeist, I used the following:

expect(page).to have_current_path('', url: true)

Ref: have_current_path

3.a. Passing hardcoded queryParams to transitionTo in EmberJS

The JavaScript widget redirects with parameters in the url, that looked something like:

It was easier than I thought to pass these queryParams along with a transitionTo:

route.transitionTo('session.register', { queryParams: { name: 'Batman', alias: 'Bruce', car: 'batmobile' }});

Ref: Query Parameters with transitionTo

3.b. Getting the queryParams object in EmberJS

Redirecting if guests aren't authorised to view page. Stashing queryParams object and pass it in transitionTo.

  beforeModelWrapper: function (route, args) {
    var transition = args[0];
    var userParams = transition.state.queryParams;
    if (!route.get('guestAllowed') && !this.get('isAuthenticated')) {
      this.set('backupTransition', transition);
      route.transitionTo('session.register', { queryParams: userParams });
      return true;

Ref: Storing and Retrying a transition

That is all.

© 2020 -