【问题标题】:Test fail with ActionView::Template::Error: undefined method `name' for nil:NilClass测试失败,ActionView::Template::Error: undefined method `name' for nil:NilClass
【发布时间】:2012-05-31 20:26:35
【问题描述】:

我正在查看 show.html.erb

 <%= @question.user.lesson_id %>

这是在浏览器上的一个数字。

我的 questions_controller.rb 是

 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

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

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

当改变视图时 show.html.erb

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

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

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

我试试这个

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

在 questions_controller.rb 上然后测试失败

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

类似问题hereherehere

【问题讨论】:

    标签: ruby-on-rails testing null


    【解决方案1】:

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

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

    【讨论】:

    • 感谢您的回复,在我的 schema.rb 中有两个表。带有 t.string "name" 的表 "lessons" 和带有 t.string "name" 的表 "tags"。也许这就是问题所在。我尝试更改数据库并查看
    【解决方案2】:

    来自this answer的解决方案

    是使用 try 方法并改变视图为

    <%= @question.user.lesson.try(:name) %>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-28
      • 1970-01-01
      • 2015-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-07
      相关资源
      最近更新 更多