Software engineering notes

First experiences with Rack::Test

leave a comment »

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

    def test_redirect_logged_in_users_to_dashboard
      authorize "bryan", "secret"
      get "/"

      assert_equal "", last_request.url
      assert last_response.ok?


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

There we go:

Loaded suite test.rb
Finished in 0.007586 seconds.

1) Error:
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

Written by Erik

October 11, 2010 at 11:04 pm

Posted in Uncategorized

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: