dimanche 7 juin 2015

How to set a default value for a method call in a instance with minitest?

I am learning ruby and TDD. I am using Minitest as my unit test framework. Currently I have a class (pair) that will be initialized with two instances of a second class (participant). To unit test it, I would like to create two mocks of participants and pass them to the initialize method:

def test_init
    participantOne = Minitest::Mock.new
    participantOne.expect(:name, "P1")
    participantOne.expect(:dept, "D1")

    participantTwo = Minitest::Mock.new
    participantTwo.expect(:name, "P2")
    participantTwo.expect(:dept, "D2")

    pair = Pair.new(participantOne, participantTwo)

    assert_equal("P1", pair.participantOne.name) #I would like to change this line
    assert_equal("P2", pair.participantTwo.name) # and this line


end

This works, but it is not 100% correct. If I change the assert equal line to

assert_equal(participantOne.name, pair.participantOne.name) #I would like to change this line

To compare the value of the stored participant with the value of the mock (which I would like to store), I get

MockExpectationError: No more expects available for :name: []

To be honest, I don't really understand it. It seems that the "expect" I set before was already "used" during the execution of my code.

This is not exactly what I am looking for. I do not want to verify how many times a method is called, I would like to define a default value to be returned when the method is called in a given instance.

How can I do that using minitest?

I made some search and I read about stubs in Minitest. But as far as I understood they are meant to stub a method call for every instance of a class.

I would like to create two participants and define their name and dept information, without using the real class, so I can focus my test in the subject under test.

ps: this is the init in my pair class

def initialize(participantOne, participantTwo)
    @participantOne = participantOne
    @participantTwo = participantTwo
end

and participant class

def initialize(name, dept)
    @name=name
    @dept=dept
end

Aucun commentaire:

Enregistrer un commentaire