Search code examples
ruby-on-railsrspecruby-on-rails-5rspec-rails

Mount additional routes in Rails specs


I want to test 3rd party sites embedding a javascript widget (provided by my Rails app) and submitting forms to an endpoint in my rails app.

To do this, I have created a dummy sinatra app that I test with Capybara:

# spec/system/widget_spec.rb

require 'sinatra/base'
class DummyApp < Sinatra::Base
  get '/form' do
    @widget_code = params[:widget_code]
    erb :form
  end
end

require 'rails_helper'

...

I'm defining this app before Rails is loaded in my spec, so that I can do the following in routes.rb:

mount DummyApp => '/dummy' if defined? DummyApp

This works if I run just this one spec, but if I run the whole suite, Rails is loaded before my DummyApp is defined.

Ideally I'd like to pull this line out of routes.rb entirely and allow my test to inject custom routes, so my routes file isn't cluttered with test-related routes.

1) Is there a way to tinker with rails routes within tests?

2) If not, what's the best way to go about testing this type of scenario?


Solution

  • There is a helper with_routing you could use (docs):

    with_routing do |set|
      set.draw do
        mount DummyApp => '/dummy'
      end
      # ...
    end