Unit testing

Posted by Brian in Rails, snacks (April 3rd, 2007)

Rails developers typically do test-driven development, so they’re writing their unit tests before they write their business rules. For example, if I was to write a keyword search method, I’d write a unit test first.

# Should find 2 because I have “red” in the test data in 2 records
assert_equal(2, Document.find_by_keywords(“red”)

# should find 0 because that term isn’t in any of the records
assert_equal(2, Document.find_by_keywords(“blue”)

# should find 2 because the word “ninja” is found on one document
# and ‘pirate’ is found in another.
assert_equal(2, Document.find_by_keywords(“ninja pirate”)

The test that I wrote gives me a clear indication of the requirement I have to implement. When these tests (and more) all pass, I know that I have my search engine finished. I don’t need to continously try various examples manually to see if I am done. It takes a lot of the manual testing away, but it also gives me more confidence that my code does what I think it does.

The hardest part about testing is learning to do it first. It takes much longer to write tests after you already have a working application, and it feels pointless. (It’s really not, but it just feels that way when you’re doing it which can be really demotivating.)

Leave a reply

:mrgreen: :neutral: :twisted: :shock: :smile: :???: :cool: :evil: :grin: :oops: :razz: :roll: :wink: :cry: :eek: :lol: :mad: :sad: