Starting Test-Driven Development
As discussed in Part 6 of this series, you have to resist the temptation to dive straight into writing the code. Take the time to think through the implications of the design ideas and write some unit tests that show how the application is supposed to work.
For the use case Club Secretary : Notify members about special events, we have three classes that are interesting: Member, Club, and ClubEvent. The class to start with is the ClubEvent, since it doesn't know anything about either of the other two classes. The data for the unit test is lifted directly from the acceptance tests (see Part 5 of this series). As usual, the filename of each file should match the name of the class, so TC_ClubEvent should be stored in a file called TC_ClubEvent.rb.require 'test/unit' require 'ClubEvent' require 'date' class TC_ClubEvent < Test::Unit::TestCase def set_up @evt = ClubEvent.new("Club AGM", Date.new(2002,4,1)) end def test_name assert_equal("Club AGM", @evt.name, "Mismatch") end def test_date assert_equal("2002-04-01", @evt.date.to_s, "Mismatch") end def test_description @evt.append_description ("Annual general meeting") @evt.append_description ("Location: TBA") assert_equal(["Annual general meeting", "Location: TBA"], @evt.description, "Mismatch in returned array") end end
With these tests in place, it's easy to implement the ClubEvent class:
class ClubEvent attr_accessor :name, :date, :description def initialize (event_name, date_of_event) @name = event_name @date = date_of_event @description = Array.new end def append_description (str) description << str # adds to end of array of lines end end