Bamdad Dashtban
Bamdad Dashtban

Reputation: 354

How to test subject with dependency?

I want to develop a card-base game in Ruby, and I want to do it in TDD way.

The first class I want to write is Player. Each player has a hand with 13 cards and on his/her turn can choose and play 1 card to pass.

I have not developed any other classes (like card, hand, ..), I want to know how I can test this subject which has dependency to other classes?

I know about Mocks but I don't know how can I use them.

For example in this scenario we know that when a player plays one card that card should have to be removed from his/her hand.

This is my code :

require "rspec"
require "lib/player"

describe Player do
  before(:each) do
    hand=mock("Hand")
    hand.should_receive(:count).and_return(13)
    subject.hand=hand
  end

  it "should choose and play a card from her/his hand" do
      subject.hand.count.should==13
      card_selected=subject.play(2)      # card #2 in his/her hand
      subject.hand.count.should=12
   end
end

Also, in the implementation we are dependent to the Hand class, how can I handle it ?

Upvotes: 3

Views: 289

Answers (1)

awendt
awendt

Reputation: 13713

I've seen my share of mocking and stubbing, and I've seen huge test suites pass even though the app was broken beyond belief because half the code didn't even exist anymore.

I've come to the conclusion that stubbing and mocking should be used with extreme care. That, and the fact that it should be introduced as late as possible.

This is one of the cases where it's too early to mock. You're mocking just because you don't have the class Hand yet.

As a sidenote, the test itself needs improvement. Take a closer look at these lines:

hand.should_receive(:count).and_return(13)
subject.hand=hand
subject.hand.count.should==13
subject.hand.count.should=12

Of course, subject.hand.count.should==13 passes, you just stubbed it to this value. And of course, subject.hand.count.should=12 passes because you didn't call ==. If you changed it to a real expectation, you'd be wondering why it fails. It fails because you stubbed Hand#count to always return 13.

What you're actually doing here is mocking part of the API under test. Don't do this. Instead, start with baby steps. This could mean:

  • You start on the inside and work your way out. So start with the innermost class, Hand in this case. Once you get to Player, all the pieces will fit together just fine without mocking.

  • You start with Player until you absolutely need the other class (do that if the argument of a "meaningful API" appeals to you). This means: Wait for a NameError on Hand. Then implement just as much of the Hand class as necessary. Then get back to Player

Also, looking at your code raises the question: Just out of curiosity, why would you want to separate a player and her hand in the first place?

Upvotes: 2

Related Questions