urlmap snippets

How to test modular Sinatra apps with Rack::Test

Tagged sinatra, rack::test, urlmap  Languages ruby

Let's say you have this in your config.ru:

run Rack::URLMap.new \
  "/" => HomeController.new,
  "/user" => UserController.new

and you want to test both / and /user at the same time.

The solution is to return an instance of Rack::Builder instead of, for example, HomeController, which this snippet does by reading config.ru and evaluating it:

def app
  eval "Rack::Builder.new {( " + File.read(File.dirname(__FILE__) + '/../config.ru') + "\n )}"
end

The code was found on the internets and might not work if Sinatra/Rack is changed.

How to test one controller in isolation

To test just one controller use this code:

def app
    Rack::Builder.new do
      run ProductsController
    end
end

or even simpler:

def app
    ProductsController
end