FactoryGirl Rspec ActionView::Template::Error: undefined method for nil:NilClass

寵の児 提交于 2019-12-11 07:15:28

问题


I'm new to rails and am trying to give TDD a try.

I have a user model that has an admin attribute that is set to nil by default and a request model.

Here's a test that I have for my request controller

it "should grant access to 'destroy'" do
        req = Factory(:request, :user => @user)
        delete :destroy, :id => req.id
        response.should be_successful
end

When I run this I get the following error:

ActionView::Template::Error:undefined method `admin' for nil:NilClass

I'm guessing this is because my views have links that only show up if the user owns the link or if they are an admin. So, I'm doing conditional testing on the admin attribute. Do I need to set the admin attribute to false?

How do I deal with this?


回答1:


I made a mistake. I tried to call user.admin in my controller when the user was nil. I created a helper method to check if user was nil before checking the admin field.

def admin?(user)
  if not user.nil?
    return user.admin
  end
  return false
end


来源:https://stackoverflow.com/questions/6035626/factorygirl-rspec-actionviewtemplateerror-undefined-method-for-nilnilclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!