类: RSpec::Core::Formatters::HtmlSnippetExtractor 私有

继承
Object
  • Object
显示全部
定义于
lib/rspec/core/formatters/html_snippet_extractor.rb

概述

此类是私有 API 的一部分。 应尽可能避免使用此类,因为它可能会在将来被删除或更改。

通过查看传入错误的回溯来提取代码片段,并使用 html 应用语法高亮和行号。

实例方法摘要 折叠

实例方法详情

#lines_around(file, line) ⇒String

此方法是私有 API 的一部分。 应尽可能避免使用此方法,因为它可能会在将来被删除或更改。

提取源文件内特定行周围的代码行。

参数

  • file (String)

    文件名

  • line (Fixnum)

    行号

返回

  • (String)

    文件内目标行周围的行(上方 2 行,下方 1 行)。

84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/rspec/core/formatters/html_snippet_extractor.rb', line 84
def lines_around(file, line)
  if File.file?(file)
    lines = File.read(file).split("\n")
    min = [0, line - 3].max
    max = [line + 1, lines.length - 1].min
    selected_lines = []
    selected_lines.join("\n")
    lines[min..max].join("\n")
  else
    "# Couldn't get snippet for #{file}"
  end
rescue SecurityError
  # :nocov: - SecurityError is no longer produced starting in ruby 2.7
  "# Couldn't get snippet for #{file}"
  # :nocov:
end

#post_process(highlighted, offending_line) ⇒String

此方法是私有 API 的一部分。 应尽可能避免使用此方法,因为它可能会在将来被删除或更改。

向所有行添加行号,并使用 html span 标签突出显示发生错误的行。

参数

  • highlighted (String)

    包含错误代码行的语法高亮片段

  • offending_line (Fixnum)

    发生错误的行

返回

  • (String)

    完成的片段

110
111
112
113
114
115
116
117
118
# File 'lib/rspec/core/formatters/html_snippet_extractor.rb', line 110
def post_process(highlighted, offending_line)
  new_lines = []
  highlighted.split("\n").each_with_index do |line, i|
    new_line = "<span class=\"linenum\">#{offending_line + i - 2}</span>#{line}"
    new_line = "<span class=\"offending\">#{new_line}</span>" if i == 2
    new_lines << new_line
  end
  new_lines.join("\n")
end

#snippet(backtrace) ⇒String

此方法是私有 API 的一部分。 应尽可能避免使用此方法,因为它可能会在将来被删除或更改。

提取与回溯相对应的代码行。

参数

  • backtrace (String)

    测试失败的回溯

返回

  • (String)

    突出显示指示测试失败位置的代码片段

参见

49
50
51
52
53
# File 'lib/rspec/core/formatters/html_snippet_extractor.rb', line 49
def snippet(backtrace)
  raw_code, line = snippet_for(backtrace[0])
  highlighted = @@converter.convert(raw_code)
  post_process(highlighted, line)
end

#snippet_for(error_line) ⇒String

此方法是私有 API 的一部分。 应尽可能避免使用此方法,因为它可能会在将来被删除或更改。

从一行代码创建片段。

参数

  • error_line (String)

    带有行号的文件名(例如 'foo_spec.rb:12')

返回

  • (String)

    文件内目标行周围的行

参见

65
66
67
68
69
70
71
72
73
# File 'lib/rspec/core/formatters/html_snippet_extractor.rb', line 65
def snippet_for(error_line)
  if error_line =~ /(.*):(\d+)/
    file = Regexp.last_match[1]
    line = Regexp.last_match[2].to_i
    [lines_around(file, line), line]
  else
    ["# Couldn't get snippet for #{error_line}", 1]
  end
end