First experiences with Rack::Test

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.

  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

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

require "rack/test"
require "test/unit"
...

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:

require "rubygems"
require "rack/test"
require "test/unit"
...

Dah! NameError: uninitialized constant HomepageTest::MyApp

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

require "rubygems"
require "sinatra"
require "rack/test"
require "test/unit"

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

  def app
    Sinatra::Application
  end
...

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

Leaning Palm HDR, "A stretch of beach along the Blue Lagoon on the atoll of Rangiroa."
Credit: vgm8383

Helpful links