RSpec integration tests with custom headers

While writing an integration test, I needed to pass a custom HTTP header to the GET request. Doing a quick scan in the Rails source (I’m using Rails 3.1.3) points me to here.

It looks like all I need is to include my custom HTTP header in a hash and pass it to the get call as the last argument.

Fairly straight forward, I came up with this

get "/api/xxxxx/xxxxx/xxxxx",
    { format: "json" },
    { authorization: "Token token=\"#{app.token}\"" }

As you can see, I trusted the doc, I used authorization as the header hash key. I was hoping it’ll be turned into HTTP_AUTHORIZATION. And you can guess, it didn’t, my request spec was failing badly, returning me HTTP 401 instead, not passing the initial authentication. It turned out that the Rails doc is lying to me. I had to fire the get call like this instead

get "/api/xxxxx/xxxxx/xxxxx",
    { format: "json" },
    { "HTTP_AUTHORIZATION" => "Token token=\"#{app.token}\"" }
Published: 2012-07-23
blog comments powered by Disqus