Adding More Features to Test Driven Development
So far, in writing code in Test Driven Development and making tests pass in TDD, we've not been doing any parsing. So, let's add a test to say we want the class to actually parse the name, not just store it. We want to be able to retrieve just the first name.
def test_first_name
assert_equal( "John", @js.first_name )
end
Run the tests and watch it fail.
>ruby tc_nameParser.rb
Loaded suite tc_nameParser
Started
E..
Finished in 0.0 seconds.
1) Error:
test_first_name(TestNameParser):
NoMethodError: undefined method `first_name' for #<NameParser:0x2c07a40 @name="John Smith">
tc_nameParser.rb:23:in `test_first_name'
3 tests, 3 assertions, 0 failures, 1 errors
Now fix it. Here, I decide the shortest distance to making this test pass is to use split in the first_name method.
class NameParser
def initialize(n)
@name = n
end
def full_name
@name
end
<b>def first_name
@name.split(/ /)[0]
end</b>
end
Run the tests and make sure they pass.
>ruby tc_nameParser.rb
Loaded suite tc_nameParser
Started
...
Finished in 0.015 seconds.
3 tests, 4 assertions, 0 failures, 0 errors

