I'm using rspec-rails (2.8.1) to functional test a rails 3.1 app using mongoid (3.4.7) for persistence. I'm trying test rescue_from for Mongoid::Errors::DocumentNotFound errors in my ApplicationController in the same way that the rspec-rails documentation for anonymous controllers suggests it could be done. But when I run the following test...
require "spec_helper"
class ApplicationController < ActionController::Base
rescue_from Mongoid::Errors::DocumentNotFound, :with => :access_denied
private
def access_denied
redirect_to "/401.html"
end
end
describe ApplicationController do
controller do
def index
raise Mongoid::Errors::DocumentNotFound
end
end
describe "handling AccessDenied exceptions" do
it "redirects to the /401.html page" do
get :index
response.should redirect_to("/401.html")
end
end
end
I get the following unexpected error
1) ApplicationController handling AccessDenied exceptions redirects to the /401.html page
Failure/Error: raise Mongoid::Errors::DocumentNotFound
ArgumentError:
wrong number of arguments (0 for 2)
# ./spec/controllers/application_controller_spec.rb:18:in `exception'
# ./spec/controllers/application_controller_spec.rb:18:in `raise'
# ./spec/controllers/application_controller_spec.rb:18:in `index'
# ./spec/controllers/application_controller_spec.rb:24:in `block (3 levels) in <top (required)>'
Why? How can I raise this mongoid error?
Mongoid's documentation for the exception shows it must be initialized. The corrected, working code is as follows:
require "spec_helper"
class SomeBogusClass; end
class ApplicationController < ActionController::Base
rescue_from Mongoid::Errors::DocumentNotFound, :with => :access_denied
private
def access_denied
redirect_to "/401.html"
end
end
describe ApplicationController do
controller do
def index
raise Mongoid::Errors::DocumentNotFound.new SomeBogusClass, {}
end
end
describe "handling AccessDenied exceptions" do
it "redirects to the /401.html page" do
get :index
response.should redirect_to("/401.html")
end
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With