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 <开发者_C百科;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
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
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
精彩评论