2

I'm having trouble creating specs for my views and requests. Some of my controllers use named_scope, like this:

 #projects_controller.rb
 @projects = Project.with_user( current_user)

 ## project.rb:
 scope :with_user, lambda {|u|  {:joins => :client, :conditions => {:clients => {:user_id => u.id} } }}

but the following spec gives an error:

Spec:

describe "GET /projects" do
    it "works! (now write some real specs)" do
      get projects_path
    end 

Error:

6) Projects GET /projects works! (now write some real specs)
     Failure/Error: get projects_path
     Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id
     # ./app/models/project.rb:9:in `block in <class:Project>'
     # /home/mping/.rvm/gems/ruby-1.9.2-rc2/gems/activerecord-3.0.0.rc/lib/active_record/named_scope.rb:95:in `call'
     # /home/mping/.rvm/gems/ruby-1.9.2-rc2/gems/activerecord-3.0.0.rc/lib/active_record/named_scope.rb:95:in `block in scope'
         # ./app/controllers/projects_controller.rb:4:in `index'

I have a similar error within my view specs:

 4) projects/show.haml renders attributes in <p>
     Failure/Error: render
     undefined method `name' for nil:NilClass
     # /home/mping/.rvm/gems/ruby-1.9.2-rc2/gems/activesupport-3.0.0.rc/lib/active_support/whiny_nil.rb:48:in `method_missing'
     # ./app/views/projects/show.haml:4:in `_app_views_projects_show_haml___1706343108022772066_34134280__4548622860215298334'

It seems to me that I need to stub the current_user method defined by authlogic in order to be able to advance. How can I spec views and requests? Thanks

Miguel Ping
  • 18,082
  • 23
  • 88
  • 136

2 Answers2

4

I just successfully used the solution here: http://spacevatican.org/2011/12/5/request-specs-and-authlogic

before(:each) do
  activate_authlogic
  @user = FactoryGirl.create(:user)
  UserSession.create @user
  cookies['user_credentials'] = "#{@user.persistence_token}::#@user.send(@user.class.primary_key)}"
end
Muntasim
  • 6,689
  • 3
  • 46
  • 69
0

Stubbing current_user can be a frustrating experience. You can get the necessary session functionality in your specs by creating a user and logging in, as recommended in the Authlogic docs. Eg.

include Authlogic::TestCase
activate_authlogic
@user = Factory.create(:user)
UserSession.create(:user)

Logging out:

session = UserSession.find
session.destroy if session
zetetic
  • 47,184
  • 10
  • 111
  • 119
  • Are you setting `assigns` in your view specs? – zetetic Sep 05 '10 at 17:28
  • I'm having the same problem. @zetetic, what assign are you talking about? The current_user? – Paul Aug 11 '11 at 15:08
  • @ThibautBarrère Have a look at this guy's breakdown of the issue you're experiencing in request specs: http://www.spacevatican.org/2011/12/5/request-specs-and-authlogic/ – Joshua Pinter Sep 30 '14 at 01:59