繁体   English   中英

Rails Minitest ActionView :: Template :: Error:nil:NilClas的未定义方法

[英]Rails Minitest ActionView::Template::Error: undefined method for nil:NilClas

一直在尝试调试此工具两天,而我只是被卡住了。 我有一个视图,我正在尝试在rails中进行测试,并且当我在浏览器中手动测试时,该视图可以完美地工作,但是在控制器测试中却不断出现此错误:

ActionView::Template::Error: undefined method "name" for nil:NilClass 这是完整的错误消息

这是测试(test / controllers / quotes_controller_test.rb):

  test "should get quotes index as browse" do
    get browse_path
    assert_response :success
  end

我渲染该部分内容的地方很破(views / quotes / browse.html.erb):

  <% if @recent_quotes.any? %>
    <aside class="recent-quotes browse-quotes col-7">
      <%= render @recent_quotes %>
    </aside>
  <% end %>

局部看起来像这样(views / quotes / _quote.html.erb):

<blockquote id="quote<%= quote.id %> blockquote">
  <small class="text-muted">
    <%= link_to quote.topic.name, artist_path(quote.topic) %>
  </small>
  <p class="mb-0"><%= link_to quote.content, quote_path(quote) %></p>

  <footer class="blockquote-footer">
      <cite title="Source">
        <%= link_to quote.speaker.name, quote.source %>
      </cite>
  </footer>
</blockquote>

控制器动作如下所示(controllers / quotes_controller.rb):

  def browse
    @artists = Artist.all
    @recent_quotes  = Quote.all.limit(7)
  end

同样,一切都在浏览器中运行良好,但是我无法通过这个简单的测试。 如果我删除了它通过的部分,那么路由工作正常。 我认为测试只是在对quote.topic.name的第一次调用中寻找name方法,而没有找到它。

但是它可以在浏览器中运行,所以我无法弄清楚该测试做错了什么。

抱歉,我的评论信誉不足,所以我将尝试回答。

您的固定装置是什么? 您是否为所有recent_quotes定义了主题艺术家(名称)?

灯具绕过所有验证,因此即使您在Quote类中拥有灯具,也不会因无效灯具而收到任何错误

在控制器中,您具有@recent_quotes = Quote.all.limit(7) 但是在固定装置中,您只为5个引号定义了发言人和主题。 这部分:

<% 30.times do |n| %>
quote_<%= n %>:
  user: jordan
  content: <%= Faker::Lorem.unique.sentence %>
  speaker_id: <%= rand(1..5) %>
  topic_id: <%= rand(6..10) %>
  created_at: <%= 42.days.ago %>
<% end %>

不起作用,因为您没有ID为1..10艺术家。 每次在灯具创建实例时,都不会从1开始设置ID,您的艺术家具有诸如503576764 ID。 因此,这部分实际上创建了引号,但它们的topic.name为nil,因为该主题不存在。

您至少需要为7个灯具手动指定Speaker&topic。 或者您需要用30.times删除零件-我不确定您是否确实需要它。 通常的做法是在灯具中使用2-3个实例。您可以在此处阅读有关灯具的更多信息

或者您可以将夹具更换为工厂 ,这将为您提供更明确,更便捷的测试记录。

还有一件事。 在这种情况下,有一个非常简单的调试工具。 只需向您的控制器添加一些行:

 def browse
    @artists = Artist.all
    @recent_quotes  = Quote.all.limit(7)
    @recent_quotes.map do |quote| 
      # you can add all what you need in this array
      p [quote.valid?, quote.errors, quote.speaker, quote.topic] 
    end
 end

并运行测试。 您将在测试输出中看到所有信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM