【问题标题】:Test_helper for a loop in the view in Ruby gemTest_helper 用于 Ruby gem 视图中的循环
【发布时间】:2016-07-18 14:40:50
【问题描述】:

此代码循环并打印整个散列,但如果散列的大小大于 4MB,它只会遍历前十个元素。

<% sections_content.each do |title, summary| %>
    <tr>
      <td style="border-bottom: 1px solid #eeeeee;"><%= raw title %></td>
    </tr>
    <tr>
      <td><%= raw summary %></td>
    </tr>
    <% break if ObjectSpace.memsize_of(sections_content) > 4194304 && index == 9 %>
<% end %>

我想为它编写一个测试,以确保在索引等于 9 时循环中断,这意味着它会循环前十个元素。

我在想这样的事情:

require 'test_helper'
test "should size> 400" do
  assert_equal(9, index, [msg])
end

测试不起作用。对测试此代码的更好方法的任何帮助[原文如此]

【问题讨论】:

    标签: ruby-on-rails ruby testing rubygems


    【解决方案1】:

    为了正确地单元测试,你首先需要使它更可测试。将相关代码移动到辅助方法中,然后测试该方法;不要把所有的逻辑都塞进视图中。

    换句话说,创建一个辅助方法(可能在./app/helpers/ 的某个地方):

    def section_summaries(sections_content)
      sections_content.map.with_index do |title, summary, index|
        # Generate HTML code...
        break if ObjectSpace.memsize_of(sections_content) > 4194304 && index == 9
      end
    end
    

    然后在你看来,调用辅助方法:

    <%= section_summaries(sections_content) %>
    

    在您的规范中,直接测试辅助方法:

    require 'test_helper'
    test "only show first 10 summaries for large dataset" do
      assert_equal(10, section_summaries(sections_content).length)
    end
    

    这只是一个粗略的指南;您的实际实现可能略有不同。要带走的关键点是尝试将逻辑隔离到方法/类中以实现单元可测试性。

    【讨论】:

    • 非常感谢,问题是这是一个 gem 一个通知 gem,文件结构有点不同。这是它的源代码:github.com/smartinez87/exception_notification如果你看一下,我将不胜感激
    • 我猜你说的是this file?它不应该有什么不同——因为无论如何你都覆盖了那个文件,你可以添加任何你喜欢的帮助方法。
    • 尽管如此说,我确实觉得你的实现有点奇怪......为什么不将@sections 限制为最多 10 个(或其他)元素,而不管视图文件?
    猜你喜欢
    • 2020-11-03
    • 2011-06-04
    • 2020-02-19
    • 1970-01-01
    • 1970-01-01
    • 2017-12-29
    • 1970-01-01
    • 2022-06-28
    • 1970-01-01
    相关资源
    最近更新 更多