Skip to content

Instantly share code, notes, and snippets.

@gevans
Last active December 20, 2015 13:09
Show Gist options
  • Save gevans/6136667 to your computer and use it in GitHub Desktop.
Save gevans/6136667 to your computer and use it in GitHub Desktop.

A quick monkey patch for use within Rails request specs. Adds boolean methods like ok?, not_found?, and unauthorized? to allow querying the name of a response status rather than its code. Within RSpec, expections can be specified easily as be_ok, be_not_found, and be_unauthorized. Like in a Rails action:

respond_with @some_object, status: 201

In my opinion, the above doesn't read as well as this:

respond_with @some_object, status: :created
# spec/requests/things_controller_spec.rb
require 'spec_helper'
describe ThingsController do
subject { response }
let(:params) { nil }
let(:request_headers) { nil }
describe 'GET /things' do
before do
get '/things', params, request_headers
end
context 'when successful (200 Ok)' do
# ...
it { should be_ok }
end
end
describe 'POST /things' do
before do
post '/things', params, request_headers
end
context 'when successful (201 Created)' do
# ...
it { should be_created }
end
context 'when supplied invalid authorization (401 Unauthorized)' do
# ...
it { should be_unauthorized }
end
context 'when supplied malformed parameters (422 Unprocessable Entity)' do
# ...
it { should be_unprocessable_entity }
end
end
describe 'DELETE /things/:id' do
before do
delete '/things', params, request_headers
end
context 'when record does not exist (404 Not Found)' do
# ...
it { should be_not_found } # That one doesn't flow very well...
end
context 'when successful (204 No Content)' do
# ...
it { should be_no_content } # That one doesn't either...
end
end
end
# spec/support/request_helpers.rb
module ActionDispatch
class TestResponse
Rack::Utils::HTTP_STATUS_CODES.each do |code, name|
class_eval <<-RUBY, __FILE__, __LINE__ + 1
def #{name.underscore.gsub(/[^a-z_]/, '_')}?
status == #{code}
end
RUBY
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment