I love test-driven development, and I love Rack apps, so I was delighted to discover the Rack::Test toolset.  But, I wasn’t able to get it working immediately using the documentation I could find, so I’m taking notes here along my journey to discovery.

I. Install Rack::Test

The docs on the Rack::Test site didn’t do me wrong.  Rack::Test installed cleanly with: 
sudo gem install rack-test II. Define some test code to get started

I grabbed the sample code from the Rack::Test site and saved it into a file called test.rb.

[sourcecode lang=“ruby”] require “rack/test”

class HomepageTest < Test::Unit::TestCase include Rack::Test::Methods

def app MyApp.new end

def test_redirect_logged_in_users_to_dashboard authorize “bryan”, “secret” get “/” follow_redirect!

assert_equal “http://example.org/redirected", last_request.url assert last_response.ok? end

end [/sourcecode]

III. Run the code

Now, this is where I stumbled. How do we run this?

I tried rackup test.rb and ruby test.rb, but both complained of an “uninitialized constant Test”, so I guess there’s a prerequisite.

I checked out the Rack::Test Gemfile and installed rspec and upgraded rack to no avail.

I’m on Mac 10.6, btw.  I’ve got rack 1.2.1 and rack-test 0.5.6.

Aha!  As per a stackoverflow thread, I learned I need to add require “test/unit” to my code, so it looks like

[sourcecode lang=“ruby”] require “rack/test” require “test/unit” … [/sourcecode]

Now, when I run ruby test.rb, it throws, `require’: no such file to load – rack/test, but this is easily solved by requiring rubygems:

[sourcecode lang=“ruby”] require “rubygems” require “rack/test” require “test/unit” … [/sourcecode]

Dah! NameError: uninitialized constant HomepageTest::MyApp

I’ll just use Sinatra, that’s my end goal anyways.

[sourcecode lang=“ruby”] require “rubygems” require “sinatra” require “rack/test” require “test/unit”

class HomepageTest < Test::Unit::TestCase include Rack::Test::Methods

def app Sinatra::Application end … [/sourcecode]

There we go:

_Loaded suite test.rb
_ _Started
_ _E
_ Finished in 0.007586 seconds.

_1) Error:
_ _test_redirect_logged_in_users_to_dashboard(HomepageTest):
_ _Rack::Test::Error: Last response was not a redirect. Cannot follow_redirect!
_

Now it’s time for bed.  Sweet dreams

[caption id=”" align=“alignnone” width=“500” caption=“Credit: vgm8383”] Leaning Palm HDR, “A stretch of beach along the Blue Lagoon on the atoll of Rangiroa.”[/caption]

Helpful links