I’m working through http://railstutorial.org (currently working on section 10.4.2 – destroying users).
My User model has a boolean admin attribute, and in the Users controller there is some simple code making use of this attribute:
def admin_user
redirect_to(root_path) unless current_user.admin?
end
The RSpec test:
describe "as a non-signed-in user" do
it "should deny access" do
delete :destroy, :id => @user
response.should redirect_to(signin_path)
end
end
And the error this test produces:
NoMethodError in ‘UsersController DELETE ‘destroy’ as a non-signed-in user should deny access’
undefined method `admin?’ for nil:NilClass
What is nil:NilClass? Why am I getting this?
edit: j., this might help:
def sign_in(user)
user.remember_me!
cookies[:remember_token] = { :value => user.remember_token,
:expires => 20.years.from_now.utc }
self.current_user = user
end
def current_user=(user)
@current_user = user
end
def current_user
@current_user ||= user_from_remember_token
end
Good news! Your rspec test found a bug!
Your controller method
is being called directly or indirectly by your controller’s delete action.
And admin_user is being called when current_user is nil. So the admin_user method is failing with the error
fix: depends on how admin_user is being called and used. Is it in a filter?
Could be changed to either of
depending on the situation….