ruby 代码测试中的 Rspec 错误

Has*_*mad 0 ruby rspec

Rspec 代码是

it "calls calculate_word_frequency when created" do
  expect_any_instance_of(LineAnalyzer).to receive(:calculate_word_frequency)
  LineAnalyzer.new("", 1) 
end
Run Code Online (Sandbox Code Playgroud)

班级代码是

def initialize(content,line_number)
@content = content
@line_number = line_number
end

def calculate_word_frequency
h = Hash.new(0)
abc = @content.split(' ')
abc.each { |word| h[word.downcase] += 1 }

sort = h.sort_by {|_key, value| value}.reverse
puts @highest_wf_count = sort.first[1]

a = h.select{|key, hash| hash == @highest_wf_count }
puts @highest_wf_words = a.keys
end
Run Code Online (Sandbox Code Playgroud)

这个测试给出了一个错误

LineAnalyzer 在创建失败/错误时调用 calculate_word_frequency:DEFAULT_FAILURE_NOTIFIER = lambda { |failure, _opts| raise failure } 正好有一个实例应该收到以下消息但没有收到:calculate_word_frequency

我如何解决此错误。我如何通过此测试?

max*_*max 5

我相信您在问“为什么我会收到此错误消息?” 而不是“为什么我的规范没有通过?”

您收到此特定错误消息的原因是您expect_any_instance_of在规范中使用了该错误,因此 RSpec 在其自己的代码中而不是在您的代码中引发了错误,主要是因为它无一例外地到达了执行的末尾,但也没有调用您的 spy。错误信息的重要组成部分,是这样的:Exactly one instance should have received the following message(s) but didn't: calculate_word_frequency。这就是你的规范失败的原因;只是显然 RSpec 决定给你一个不太有用的异常和回溯。

今天我的一个规格遇到了同样的问题,但没有比预期失败更严重的问题。希望这有助于为您清除它。