Alex Chaffee's blog
def capturing_output
output = StringIO.new
$stdout = output
yield
output.string
ensure
$stdout = STDOUT
end
then...
it "exits immediately from --version" do
output = capturing_output do
lambda {
Erector.new(["--version"])
}.should raise_error(SystemExit)
end
output.should == Erector::VERSION + "\n"
end
Here's an RSpec trick I discovered yesterday. Sometimes when you're writing a test you want to loop over some precondition data. But if you do a loop inside your test (or spec), then all the cases will be subsumed in a single test method (or "it" block). This means you'll have the following problems:
- The first case to fail will cause the rest of the cases not to run. It'd be nice to see them all in a single test run.
- You won't take advantage of RSpec's cool self-documenting trick of labeling each it block with a full description of the failure, and it'll be harder to debug which case failed.
- If you're calling into Rails (e.g. in a View spec), you'll only be able to call certain methods -- especially
render-- once per test method. That means that you simply can't use a loop inside a method to collapse redundant tests into a single block.
Ruby to the rescue! Instead of looping inside your it block, loop outside your it block.







