FactoryGirl Rspec ActionView::Template::Error: nil:NilClass 的未定义方法 [英] FactoryGirl Rspec ActionView::Template::Error: undefined method for nil:NilClass
问题描述
我是 Rails 的新手,正在尝试尝试 TDD.
I'm new to rails and am trying to give TDD a try.
我有一个用户模型,它有一个默认设置为 nil 的 admin 属性和一个请求模型.
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
运行时出现以下错误:
ActionView::Template::Error:undefined method `admin' for nil:NilClass
我猜这是因为我的视图中的链接只有在用户拥有链接或者他们是管理员时才会显示.所以,我正在对 admin 属性进行条件测试.是否需要将 admin 属性设置为 false?
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?
我该如何处理?
推荐答案
我犯了一个错误.当用户为零时,我试图在我的控制器中调用 user.admin.我创建了一个辅助方法来检查用户是否为 nil,然后再检查 admin 字段.
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
这篇关于FactoryGirl Rspec ActionView::Template::Error: nil:NilClass 的未定义方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!