1

I would like to assert that a particular method was called, but I don't want to mock/stub the method - I want to include that code in the test as well.

For example, in Ruby, something like:

def bar()
  #stuff I want to test
end

def foo()
  if condition
    bar()
  end

  #more stuff I want to test
end

# The test:

foo()
assert_called :bar

Does anyone have a suggestion (or a better way to go about it)? My actual code is quite a bit more complex, so please don't take the simplicity of the example into account.

Vega
  • 27,856
  • 27
  • 95
  • 103
Daniel Tsadok
  • 573
  • 5
  • 10

2 Answers2

0

It's really a good way to make it two test cases, one would call foo() and check if bar() is called and another to check if bar() does it's thing well. When you're testing foo(), you should know what bar() should return.

farnoy
  • 7,356
  • 2
  • 20
  • 30
0

Perhaps something like:

require 'set'

class Class
  def instrument
    self.instance_methods.each do |m|
      old = method(m)
      define_method(m) do |*a,&b|
        @__called__ ||= Set.new
        @__called__ << m
        old.bind(self).call(*a,&b)
      end
    end
  end
end

class Object
  def assert_called(method)
    if not (@__called__ && @__called__.include?(method))
      # You will have to figure out how to make this equivalent to a failing
      #   assertion for your favorite test framework
      raise "Assertion failed! #{method} has not been called"
    end
  end
end

Then after defining your classes, but before running tests:

FooClass.instrument

Note that I haven't tested this code yet!

Alex D
  • 29,755
  • 7
  • 80
  • 126
  • Daniel, are you familiar enough with Ruby metaprogramming to take the idea which I am demonstrating and make it reality? – Alex D Feb 17 '12 at 21:25
  • I get the gist of it - that is definitely the Ruby approach :-) I will probably do it more explicitly for the methods I actually test: old = method(:foo) define_method(:foo) do ... end Thanks! – Daniel Tsadok Feb 21 '12 at 19:17
  • Glad to hear it was helpful! Kind regards – Alex D Feb 21 '12 at 20:10