Skip to content

Instantly share code, notes, and snippets.

@gaahrdner
Created March 5, 2012 08:31

Revisions

  1. gaahrdner revised this gist Mar 5, 2012. 1 changed file with 3 additions and 5 deletions.
    8 changes: 3 additions & 5 deletions gistfile1.rb
    Original file line number Diff line number Diff line change
    @@ -31,11 +31,9 @@ def show

    describe ApplicationsController do
    context "for an application that doesn't exist" do
    controller do
    def show
    raise ActiveRecord::RecordNotFound
    end
    end
    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'
  2. gaahrdner revised this gist Mar 5, 2012. 1 changed file with 9 additions and 1 deletion.
    10 changes: 9 additions & 1 deletion gistfile1.rb
    Original file line number Diff line number Diff line change
    @@ -42,4 +42,12 @@ def show
    response.status.should == 404
    end
    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)>'
  3. gaahrdner created this gist Mar 5, 2012.
    45 changes: 45 additions & 0 deletions gistfile1.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,45 @@
    ### 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
    controller do
    def show
    raise ActiveRecord::RecordNotFound
    end
    end

    it "should return a 404" do
    get :show, :format => :json, :id => 'does_not_exist'
    response.status.should == 404
    end
    end
    end