Dishcandanty
Dishcandanty

Reputation: 410

Stub and Mock Minitest

I'm trying to implement and learn testing (seems like minitest is the way to go). And I am failing miserably to test a internal module class method.

Here's more or less the usecase I am trying to do. (And maybe I am going at this completely the wrong way)

module Zombie
  class << self
    # This is the method/code I want to test/execute
    def intimidate
      roar('slardar')
    end

    # This is the method that is internal, that I want to stub.
    # Actual method(not this mocked one) is stateful. So I want to have 
    # mocked predefined data. 
    def roar(a)
      'rawrger' + a
    end
  end
end

# Test Thingy
class ZombieTest < Minitest::Test
  def test_mr_mock
    @mock = Minitest::Mock.new
    @mock.expect(:roar, 'rawrgerslardar', ['slardar'])
    Zombie.stub :roar, @mock do
      Zombie.intimidate
    end
    @mock.verify
  end
end

Upvotes: 3

Views: 999

Answers (1)

yenshirak
yenshirak

Reputation: 3106

You can use a lambda to pass the parameter:

class ZombieTest < Minitest::Test
  def test_mr_mock
    @mock = Minitest::Mock.new
    @mock.expect(:roar, 'rawrgerslardar', ['slardar'])
    Zombie.stub :roar, ->(a) { @mock.roar(a) } do
      Zombie.intimidate
    end
    @mock.verify
  end
end

Upvotes: 3

Related Questions