Wednesday, 26 September 2007

Checking response codes

I'm getting up to full speed with Rspec at the moment. It's interesting how much is missing from Rspec_on_Rails compared to the standard test assertions - particularly when you start testing APIs.

Anyway here's a few quick helper method which you stick in spec_helper.rb within the Spec::Runner.configure block so that they are available to all your specifications.

The first set switches SSL on and off. I use them in the before blocks.
  def deactivate_ssl
request.env['HTTPS']='off'
end

def activate_ssl
request.env['HTTPS']='on'
end

The next patches a hole in the Rspec on Rails matchers, which seems to lack a wrapper around assert_response.

The helper function
  def status_code(type)
if type.is_a?(Symbol)
ActionController::StatusCodes::SYMBOL_TO_STATUS_CODE[type]
else
type
end
end

Then you can write the following specifications, e.g:
    response.response_code.should == status_code(:created)

Of course this would be better in a custom matcher. Over to you.