Haseeb Ahmad
Haseeb Ahmad

Reputation: 8740

Rspec error in ruby code testing

Rspec code is

it "calls calculate_word_frequency when created" do
  expect_any_instance_of(LineAnalyzer).to receive(:calculate_word_frequency)
  LineAnalyzer.new("", 1) 
end

Code of class is

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

This test gives an error

LineAnalyzer calls calculate_word_frequency when created Failure/Error: DEFAULT_FAILURE_NOTIFIER = lambda { |failure, _opts| raise failure } Exactly one instance should have received the following message(s) but didn't: calculate_word_frequency

How I resolve this error.How I pass this test?

Upvotes: 1

Views: 3108

Answers (2)

max
max

Reputation: 319

I believe you were asking "Why do I get this error message?" and not "Why does my spec not pass?"

The reason you're getting this particular error message is you used expect_any_instance_of in your spec, so RSpec raised the error within its own code rather than in yours essentially because it reached the end of execution without an exception, but without your spy being called either. The important part of the error message is this: Exactly one instance should have received the following message(s) but didn't: calculate_word_frequency. That's why your spec failed; it's just that apparently RSpec decided to give you a far less useful exception and backtrace.

I ran into the same problem with one of my specs today, but it was nothing more serious than a failed expectation. Hopefully this helps clear it up for you.

Upvotes: 9

user229044
user229044

Reputation: 239531

The entire point of this test is to insure that the constructor invokes the method. It's written very clearly, in a very straight forward way.

If you want the test to pass, modify the constructor so it invokes the method.

Upvotes: 2

Related Questions