Reputation: 2382
In my people_controller_spec.rb I have
before(:each) do
@office = FactoryGirl.create(:office)
@organization = FactoryGirl.create(:organization)
@user = FactoryGirl.create(:user, organization: @organization)
@request.session['user_id'] = @user.id
@request.session['current_organization_id'] = @user.organization.id
end
and I have this application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery
private
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
def current_organization
if session[:current_organization_id]
Organization.find(session[:current_organization_id])
else
@current_organization ||= Organization.find(current_user.organization_id)
end
end
helper_method :current_user
helper_method :current_organization
end
The session hash does not seem to persist inside the application_controller.rb that is why I get these kinds of test errors where @current_user in the application_controller.rb is nil
6) PeopleController index sorts all people alphabetically by first_name
Failure/Error: get :index, {search: {meta_sort: "first_name.asc"}}, valid_session
NoMethodError:
undefined method `organization_id' for nil:NilClass
# ./app/controllers/application_controller.rb:15:in `current_organization'
# ./app/controllers/people_controller.rb:107:in `get_orgs'
# ./spec/controllers/people_controller_spec.rb:71:in `block (3 levels) in <top (required)>'
I have already done everything but failed.
I use rails (3.2.9) and rspec-rails 2.12.2
I SOLVED THE PROBLEM AFTER SEEING THIS Devise Test Helper - sign_in does not work
I just removed all the "valid_session" method call.
Upvotes: 3
Views: 1635
Reputation: 7196
In your before :each
block set the session with:
session[:user_id] = @user.id
session[:current_organization_id] = @user.organization.id
This uses the session helper provided by the rspec controller macros. Also I'm not sure if the session is a HashWithIndifferentAccess
like params
but either way its good to keep to using the same key type.
Upvotes: 5