0

I have module Database with method generate_from_database that spins for loops and calls method get_length. How can I test if get_length was called n times, by using rspec or mocha?

module Database
class Length < ActiveRecord::Base
  def get_length(i,j)
    ...
  end
end
def Database.generate_from_database
  ...
for i in 0...size
  for j in 0...size
    Length.new.get_length(i+1,j+1))
end
end
Vega
  • 27,856
  • 27
  • 95
  • 103
Mario
  • 335
  • 7
  • 20

2 Answers2

0

You could so something like:

Length.should_receive(:get_length).exactly(n).times

More info: http://rspec.info/documentation/mocks/message_expectations.html

pjaspers
  • 120
  • 1
  • 7
  • I did like that: Length.should_receive(:get_length).exactly(10).times Database.generate_from_database and I got failures: was expected 10, received 0, but I know that generate_from_database calls 10 times get_length. So why rspec doesn't see calls? – Mario Dec 01 '10 at 14:10
  • @Mario. Just a shot in the dark, but perhaps its a namespace issue? Try Database::Length. – Mark Thomas Dec 01 '10 at 14:22
  • @Mark. Thanks for shot, but method generate_from_database isn't class Length method.. Maybe that's a problem – Mario Dec 01 '10 at 14:36
  • @Mario. Are you doing this with a mock? – Mark Thomas Dec 01 '10 at 14:42
0

This:

mock_length = mock("length")
Length.should_receive(:new).exactly(n).times.and_return(mock_length)
mock_length.should_receive(:get_length).exactly(n).times

should work.

Jonathan
  • 3,203
  • 2
  • 23
  • 25