Last Updated: April 24, 2018
·
10.97K
· alxndr

Rails: add a route for a test

To test a feature flag implementation, we create a one-off controller in the test and check the response codes for getting its #index. We don't want the route for this controller in our actual routes.rb, so I wrapped it in a before block of our test:

describe FeatureTestController, :type => :controller do
  before do
    Rails.application.routes.draw do
      match '/feature_test' => 'feature_test#index'
    end
  end
  after do
    Rails.application.reload_routes!
  end
  describe '#index' do
    # ...
  end
end

2 Responses
Add your response

simpler/dry version

describe ApplicationTestController do
  routes ApplicationTestController
 ... tests ...
end



def self.routes(controller)
    before do
      controller_name = controller.to_s.underscore.chomp('_controller')
      Rails.application.routes.draw do
        match "test/:action", controller: controller_name, via: [:get, :post, :patch, :delete]
      end
    end

    after do
      Rails.application.reload_routes!
    end
  end
over 1 year ago ·

it should Rails.application.routes.append instead of Rails.application.routes.draw, because #draw resets all existing routes

over 1 year ago ·