2
votes

I have a rails project that serves a JSON API with tests written in RSpec. Often when running specs (request specs, specifically), I’m interested in seeing some details about the HTTP request/response...i.e. the request URL, request body, and response body, ideally JSON pretty-formatted for readability. This isn't for the purposes of documentation but rather as part of the development / debugging process.

I have a helper method I wrote which does this...you just drop a method call into your spec and it prints this stuff out.

But, seems like it would be better if there was a switch that’s part of the running specs. RSpec has custom formatters which I thought might be the right direction, but in trying to build one, I can't figure out how to get access to the request/response objects like you can from inside of your spec.

How can I access the request/response objects in my custom RSpec formatter? Or, perhaps another way to approach the problem?

1

1 Answers

0
votes

Here's an approach:

Assuming a rails project, in spec_helper.rb, define a global "after" hook like so:

config.after(:each) do #runs after each example
  if ENV['PRINTHTTP']
    #use request/response objects here, e.g. puts response.status
  end   
end

Then, you can conditionally enable by adding the environmental variable on the command-line:

$ PRINTHTTP=1 rspec