Search code examples
rubytestingsinatrarackrack-test

Can I use rack-test for deployment tests?


I've built a simple api in Sinatra, with the purpose of setting up a deployment pipeline using Docker. I'm at a stage where I could easily switch Sinatra for something else and there's currently one reason why I might do so.

I once wrote an api using Express and it was trivial to reuse the tests to test a deployment:

# Testing the code
chai.request(app)
  .get('/')

# Testing a deployment
chai.request('http://localhost:8080')
  .get('/')

Examples from: https://github.com/chaijs/chai-http#integration-testing

Now I am wondering if I can accomplish the same with rack-test and Sinatra. Simply sending a URL, instead of the app, crashes. So is there an easy way to accomplish this? I suppose I could write a testing framework on top of rack-test, but I'm not sure it's worth it, even though I do prefer Ruby over Javascript and Sinatra over Express.


Solution

  • I realised that I should be able to write a rack app that forwards all requests to the environment I want to run deployment tests against. So I went to Google and found a gem that does just that: rack-proxy

    Here's how to write a simple rack app that redirects requests to your server:

    require 'rack/proxy'
    
    class Foo < Rack::Proxy
      def rewrite_env(env)
        env["HTTP_HOST"] = "api.example.com"
        env
      end
    end
    

    Then I ran my tests against Foo.new they succeeded. I checked the logs of that environment and I can confirm that my tests were in fact running against that environment.

    Foo may not be the best name for such a proxy and you may not want the host name hardcoded, but I'm sure you can figure out how to make this work in your project if you need it.