Keeping Things Organized
Just like other code, test suites tend to grow in both size and complexity throughout the lifecycle of a project. The following techniques help keep things tidy and well factored, allowing your tests to continue to serve as a road map to your project.
Embedding Tests in Library Files
If you are working on a very small program or library, and you want to be able to run your tests while in development, but then require the code as part of another program later, there is a simple idiom that is useful for embedding your tests:
class Foo
...
end
if __FILE__ == $PROGRAM_NAME
require "test/unit"
class TestFoo < Test::Unit::TestCase
#...
end
endSimply wrapping your tests in this if statement
will allow running ruby foo.rb to
execute your tests, while require
"foo" will still work as expected without running the tests.
This can be useful for sharing small programs with others, or for
writing some tests while developing a small prototype of a larger
application. However, once you start to produce more than a few test
cases, be sure to break things back out into their normal directory
structure. Giant files can be a bit unwieldy to deal with, and it is a
bit awkward (even though it is possible) to treat your
lib/ directory as if it were also your test
suite.
Test Helpers
When you begin to chain together a large amount of test cases, you
might find that you are repeating some information across them. Some of
the most common things in this regard are require statements and ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access