Manasi Salvi

TDD Lesson 4

Exercise 49 of Learn Ruby the Hard Way you’re required to write the tests based on the code given to you. After working through the last exercise, this somehow made a lot more sense.

I used the Ruby docs Module on Test::Unit::Assertions for this exercise. I stuck to the assert_equal and assert_not_equal methods to test whether the ‘expected was equal to actual’ or ‘not equal to actual’ respectively and the assert_raise method to raise an exception.

The assert_raise method was tricky to work with initially as there weren’t many beginner level friendly code examples but with a bit of trial and error we got there.

The code provided in the book also required a bit of tweaking so the test file would run. Here are some examples of my test code for the exercise 49.

parsing a subject parser.rb

def self.parse_subject(word_list)
  self.skip(word_list, 'stop')
  next_word = peek(word_list)

      if next_word == 'noun'
        return self.match(word_list, 'noun')
      elsif next_word == 'verb'
        return ['noun', 'player']
      else
        raise ParserError.new("Expected a verb next.")
      end
  end

test_parser.rb

def test_parse_subject()
	assert_equal((Sentence.parse_subject([["noun", "princess"], ["verb", "eat"]])), ["noun", "princess"], ["noun", "player"])
	assert_equal((Sentence.parse_subject([["verb", "eat"],["noun", "princess"]])), ["noun", "player"])
	assert_equal((Sentence.parse_subject([["noun", "princess"], ["stop", "the"]])), ["noun", "princess"])
	assert_not_equal((Sentence.parse_subject([["verb", "eat"], ["noun", "princess"]])), ["verb", "eat"], ["verb", "player"])
	assert_raise ParserError do 
		Sentence.parse_subject(nil)
	end
	assert_raise ParserError do 
		Sentence.parse_subject(["direction", "north"])
	end
end

parsing a sentence parser.rb

def self.parse_sentence(word_list)
    subject = self.parse_subject(word_list)
    verb = self.parse_verb(word_list)
    object = self.parse_object(word_list)
  

    return Sentence.new(subject, verb, object)
  end
 

test_parser.rb

def test_sentence()
	sentence = Sentence.parse_sentence([["noun", "princess"], ["verb", "run"], ["stop", "the"], ["direction", "north"]])
	assert_equal(sentence.subject, "princess")
	assert_equal(sentence.object, "north")
	assert_equal(sentence.verb, "run")
end
 

comments powered by Disqus