Adrian Carolli
Adrian Carolli

Reputation: 695

How do I test the Application Controller in rspec (get request)?

I want to test a get request in my application controller, my spec looks like:

describe "GET some_get_method" do 
     it "should work" do
       get :some_get_method
    end
  end

But I recieve the following error when I do this:

Failure/Error: get :some_get_method
     AbstractController::ActionNotFound:
       The action 'some_get_method' could not be found for ApplicationController

My application controller looks like:

def some_get_method
    vari = params[:vari]

    if !vari
      render_something
      return false
    end
    true
  end

In my routes I have:

namespace :application do
    get 'some_get_method/', :action => :some_get_method
  end

Upvotes: 2

Views: 2393

Answers (1)

rjz
rjz

Reputation: 16510

It probably isn't appropriate to spec ApplicationController directly for functional testing, as your real interest is in the behavior of the controllers derived from it.

For unit testing the methods within ApplicationController, however, you could create a stub controller within the spec file (or, more appropriately, a test helper) that does nothing but expose the methods you want to test in ApplicationController:

class StubController < ApplicationController
end

You can now test Stub's methods (really Application's methods) directly without having to try and instantiate an abstract class.

Set up routing

If you need to test rendering, one approach might be to add a test-only route accessible to RSpec's request handlers:

# in config/routes.rb
unless Rails.env.production?
  namespace :stub do
    get 'some_get_method', :action => :some_get_method
  end
end

# in spec
describe "GET some_get_method" do 
  it "should work" do
     get :some_get_method
     # test
  end
end

Upvotes: 1

Related Questions