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
# should find 0 because that term isnâ€™t in any of the records
# 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.)