0

I'm writing tests with rspec for my application controller in my rails app (written in Rails 4) and I'm running into a problem where it doesn't recognize the route for the HTTP request I'm sending. I know there's a way to do this using MyApp::Application.routes but I'm not able to get it working.

#application_controller_spec.rb

require 'spec_helper'


class TestController < ApplicationController

  def index; end

end

describe TestController do
  before(:each) do
    @first_user = FactoryGirl.create(:user) 
      # this is to ensure that all before_filters are run
    controller.stub(:first_time_user)
    controller.stub(:current_user)
end

describe 'first_time_user' do
  before(:each) do
    controller.unstub(:first_time_user)
  end

  context 'is in db' do
    before(:each) do
      @user = FactoryGirl.create(:user)
      controller.stub(:current_user).and_return(@user)
    end

    it 'should not redirect' do
      get :index
      response.should_not be_redirect
    end
  end

  context 'is not in db' do

    context 'session[:cas_user] does not exist' do
      it 'should return nil' do
        get :index
        expect(assigns(:current_user)).to eq(nil)
      end
    end

    it "should redirect_to new_user_path" do
      controller.stub(:current_user, redirect: true).and_return(nil)
      get :index
      response.should be_redirect
    end
  end
end

The error I'm getting right now is

No route matches {:action=>"index", :controller=>"test"}

I would add the test#index route to config/routes.rb, but it doesn't recognize the Test Controller, so I want to do something like

MyApp::Application.routes.append do
  controller :test do
    get 'test/index' => :index
  end
end

but I'm not sure where to add this or if this even works in rspec. Any help would be great!

Cilantro Ditrek
  • 1,047
  • 1
  • 14
  • 26
  • How do you mean: "I would add the test#index route to config/routes.rb, but it doesn't recognize the Test Controller" ?? Add the route to routes.rb and do a "rake routes" from the terminal and check the output. Could be an issue with singular/plural and the generation of the controller name. – Peter Andersson Nov 13 '13 at 21:45
  • Sorry, that wasn't clear-- when I rake routes, it throw "rake aborted! missing :controller" The problem is the Test Controller only exists in the file "application_controller_spec.rb" – Cilantro Ditrek Nov 13 '13 at 21:51

1 Answers1

0

If you are trying to test your ApplicationController, see this RSpec documentation about it. You will need to define methods like index inside the test, but it works well.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366