It's so easy to create little single-file apps in Sinatra that it almost seems a shame to start a second file just for tests. The other day Dan and I decided to see if we could create a Sinatra app with everything - including the tests - baked right in. Here's what we came up with.
The code switches modes on the name of the executable used to run the file. If we run it with the spec command, we get a test run:
$ spec -fs sinatra-tests-baked-in.rb
Example App
- should serve a greeting
- should serve content as text/plain
Finished in 0.007221 seconds
2 examples, 0 failures
Otherwise, if we call it as a Ruby program, it runs the Sinatra server as we would expect:
$ ruby sinatra-tests-baked-in.rb
== Sinatra/0.9.1.1 has taken the stage on 4567 for development with backup from Thin
>> Thin web server (v1.0.0 codename That's What She Said)
>> Maximum connections set to 1024
>> Listening on 0.0.0.0:4567, CTRL+C to stop
And there you have it: a true single-file application, specs and all.
