测试失败,ActionView::Template::Error: undefined method `name' for nil:NilClass [英] Test fail with ActionView::Template::Error: undefined method `name' for nil:NilClass

查看:63
本文介绍了测试失败,ActionView::Template::Error: undefined method `name' for nil:NilClass的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查看 show.html.erb

I have on view show.html.erb

 <%= @question.user.lesson_id %>

这是浏览器上的一个数字.

and this is on browser a number.

我的 questions_controller.rb 是

my questions_controller.rb is

 def show
    @question = Question.find(params[:id])
    @comments = @question.comments.all
    if user_signed_in?
            @rating_currentuser = @question.ratings.find_by_user_id(current_user.id)
            unless @rating_currentuser
            @rating_currentuser = current_user.ratings.new
   end
 end

和我的 questions_controller_test.rb

and my questions_controller_test.rb

   test "should show question signed in" do
    sign_in users(:user2)
    get :show, :id => @question_user1.to_param
    assert_response :success
   end

一切正常(浏览器和测试)

and everything is ok (browser and testing)

更改视图时 show.html.erb

when change view show.html.erb

   <%= @question.user.lesson.name %>

我对浏览器没问题,但测试失败

I am OK with browser but fail testing with

   ActionView::Template::Error: undefined method `name' for nil:NilClass.

我试试这个

  @name = Lesson.find(params[:id])

on questions_controller.rb 然后测试失败

on questions_controller.rb then test fail with

  Expected response to be a <:success>, but was <302>

类似问题这里 此处此处

推荐答案

使用 try 可能会掩盖潜在的问题.

Using try can potentially mask the underlying problem.

例如,当我出现此错误时,是因为我没有在没有修复正确的外键引用的情况下创建模型对象 - 视图正在使用具有 name 属性的 FK 关联进行渲染 - 例如产品.产品类型.名称​​.如果我使用 try 来解决它,它会在我的测试中掩盖这个错误,这在测试中是不受欢迎的.一旦我添加了正确的引用,一切都可以正常工作,不需要 try(:name).

For example, when I had this error it was because I wasn't creating a model object without the correct foreign key references fixed up - the view was rendering using the FK association with the name attribute - e.g. Product.ProductType.name. If I had used try to workaround it, it would have masked this fault in my test which would have been undesirable in the test. Once I had added the correct references everything worked as it should have with no need for try(:name).

这篇关于测试失败,ActionView::Template::Error: undefined method `name' for nil:NilClass的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆