Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rspec stubing view for anonymous controller

I'm trying to test a method on the application controller that will be used as a before filter. To do this I have setup an anonymous controller in my test with the before filter applied to ensure that it functions correctly.

The test currently looks like this:

describe ApplicationController do
  controller do
    before_filter :authenticated

    def index      
    end
  end

  describe "user authenticated" do
    let(:session_id){"session_id"}
    let(:user){OpenStruct.new(:email => "[email protected]", :name => "Colin Gemmell")}

    before do
      request.cookies[:session_id] = session_id
      UserSession.stub!(:find).with(session_id).and_return(user)
      get :index
    end

    it { should assign_to(:user){user} }

  end
end

And the application controller is like this:

class ApplicationController < ActionController::Base
  protect_from_forgery

  def authenticated
    @user = nil
  end
end

My problem is when ever I run the test I'm getting the following error

1) ApplicationController user authenticated 
   Failure/Error: get :index
   ActionView::MissingTemplate:
     Missing template stub_resources/index with {:handlers=>[:erb, :rjs, :builder, :rhtml, :rxml, :haml], :formats=>[:html], :locale=>[:en, :en]} in view paths "#<RSpec::Rails::ViewRendering::PathSetDelegatorResolver:0x984f310>"

According to the docs the view is not rendered when running controller tests however this points to no stub existing for this action (which is understandable as the view doesn't exist)

Anyone have a clue how to solve this problem or stub the view out.

Cheers Colin G

like image 502
pythonandchips Avatar asked Feb 28 '11 21:02

pythonandchips


2 Answers

Couldn't you get round this by putting:

render :nothing => true

inside the #index action?

like image 57
cjwright83 Avatar answered Nov 15 '22 09:11

cjwright83


A better way to do this is to create a dummy views directory. I wouldn't use spec/views, as that is actually for valid view tests. Instead, create this directory structure:

spec/test_views/anonymous
     index.html.erb
     ... and any other anonymous controller templates you happen to need ...

index.html.erb can be empty, as noted, since rspec2 is only checking for existence, not for content.

Then in your application.rb initializer, place this line:

# add a view directory for the anonymous controller tests
config.paths['app/views'] << "spec/test_views" if Rails.env.test?

Note: I tried putting that line in test.rb, for some reason doesn't seem to work there.

like image 4
Rob Avatar answered Nov 15 '22 09:11

Rob