【问题标题】:Rspec pass test in ruby testingruby 测试中的 Rspec 通过测试
【发布时间】:2015-11-23 20:30:00
【问题描述】:

我有一个 Rspec 测试如下:

it "calculates highest count words across lines to be will, it, really" do
  solution.analyze_file

  expect(solution.highest_count_words_across_lines).to be nil

  solution.calculate_line_with_highest_frequency

  words_found = solution.highest_count_words_across_lines.map(&:highest_wf_words).flatten
  expect(words_found).to match_array ["will", "it", "really"] 
end  

报错

Solution#calculate_line_with_highest_frequency calculates highest count words across lines to be will, it, really
     Failure/Error: words_found solution.highest_count_words_across_lines.map(&:highest_wf_words).flatten
   NoMethodError:
       undefined method `highest_wf_words' for "really":String
     # ./spec/solution_spec.rb:38:in `map'
     # ./spec/solution_spec.rb:38:in `block (3 levels) in <top (required)>'

另一方面,如果我写这个测试没有

.map(&:highest_wf_words).flatten

然后就通过了。

@highest_count_words_across_lines = ["really","will","it"]

我怎样才能使这个测试通过,同时包括映射:

.map(&:highest_wf_words).flatten?

【问题讨论】:

  • 您能否正确格式化您的代码/错误消息?并改写你的问题标题?
  • 我更新了我的问题。请立即查看
  • 有错误说您正在调用'really'.highest_wf_words。 high_wf_words() 方法长什么样子?
  • 请贴出highest_count_words_across_lineshighest_wf_words方法的代码。而且,在未来,使用更多更短的方法名称
  • 这两个都是实例变量

标签: ruby dictionary rspec


【解决方案1】:

solution.highest_count_words_across_lines 是一个字符串数组。当您执行此操作时:solution.highest_count_words_across_lines.map(&amp;:highest_wf_words) 您正在对每个数组项调用 highest_wf_words,并且没有为字符串定义该方法(这就是错误消息所说的)。

我猜实际上你想要这样的东西:

words_found = solution.highest_count_words_across_lines.map( |x| highest_wf_words(x)).flatten

更新

如果您的映射目的是让 words_found 仅包含 highest_wf_words,假设这是一个数组,那么您可以这样做:

words_found = solution.highest_count_words_across_lines.flatten & highest_wf_words

.

[1,2,3] & [2,3,4]
=> [2, 3]

【讨论】:

  • 我接受这个问题,因为它是正确的。它有助于我理解。但我的问题是我无法更改此解决方案。highest_count_words_across_lines.map(&:highest_wf_words) 我做的哪个更改匹配?
猜你喜欢
  • 1970-01-01
  • 2019-04-04
  • 1970-01-01
  • 2015-07-08
  • 2017-01-24
  • 1970-01-01
  • 1970-01-01
  • 2013-11-18
  • 1970-01-01
相关资源
最近更新 更多