Skip to content

Instantly share code, notes, and snippets.

@gaahrdner
Created March 5, 2012 08:31
Show Gist options
  • Save gaahrdner/1977473 to your computer and use it in GitHub Desktop.
Save gaahrdner/1977473 to your computer and use it in GitHub Desktop.
### application_controller.rb
class ApplicationController < ActionController::Base
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
private
def not_found(exception)
respond_to do |format|
h = { :status => "error", :message => exception.message }
format.html { render :file => "#{RAILS_ROOT}/public/404.html", :status => :not_found }
format.json { render :json => h, :status => :not_found }
format.xml { render :xml => h, :status => :not_found }
end
end
end
### applications_controller.rb
class ApplicationsController < ApplicationController
respond_to :html, :xml, :json
def show
@application = Application.find(params[:id], :include => includes)
respond_with(@application) do |format|
format.xml
format.json
end
end
end
### applications_controller_spec.rb
describe ApplicationsController do
context "for an application that doesn't exist" do
before do
Application.should_receive(:find).with('does_not_exist').and_raise(ActiveRecord::RecordNotFound)
end
it "should return a 404" do
get :show, :format => :json, :id => 'does_not_exist'
response.status.should == 404
end
end
end
### rspec output
1) ApplicationsController JSON GET :show for an application that doesn't exist should return a 404
Failure/Error: raise ActiveRecord::RecordNotFound
ActiveRecord::RecordNotFound:
ActiveRecord::RecordNotFound
# ./spec/controllers/applications_controller_spec.rb:54:in `index'
# ./spec/controllers/applications_controller_spec.rb:60:in `block (5 levels) in <top (required)>'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment