Rails Functional Test of Arbitrary or Custom URLs

Craig Walker picture Craig Walker · Nov 1, 2009 · Viewed 7.1k times · Source

I have a RESTful resource in my Rails app called "Photo". I'm using Paperclip to serve different "styles" of my photos (for thumbnails and the like), and I'm using a custom route to RESTfully access those styles:

map.connect "photos/:id/style/*style", :controller => "photos", :action => "show"

That's working fine, but I want to write a test to make sure it stays that way.

I already have a functional test to call the Photo controller's show action (generated by scaffold in fact):

test "should show photo" do
  get :show, :id => photos(:one).to_param
  assert_response :success
end

That tests the execution of the action at the URL "/photo/1". Now I want to test the execution of the URL "/photo/1/style/foo". Unfortunately, I can't seem to get ActionController::TestCase to hit that URL; the get method always wants an action/id and won't accept a URL suffix.

How do I go about testing a custom URL?

Update

While checking on @fernyb's answer I found this snippet in the same rdoc

In tests you can simply pass the URL or named route to get or post. def send_to_jail get '/jail' assert_response :success assert_template "jail/front" end

However, when I actually try that, I get an error message:

test "should get photo" do
  get "/photos/1/style/original"
  assert_equal( "image/jpeg", @response.content_type )
end  

ActionController::RoutingError: No route matches {:action=>"/photos/1/style/original", :controller=>"photos"}

I wonder if I'm doing something wrong.

Answer

fernyb picture fernyb · Nov 1, 2009

Use assert_routing to test routes:

assert_routing("/photos/10/style", :controller => "photos", :action => "show", :id => "10", :style => [])

assert_routing("/photos/10/style/cool", :controller => "photos", :action => "show", :id => "10", :style => ["cool"])

assert_routing("/photos/10/style/cool/and/awesome", :controller => "photos", :action => "show", :id => "10", :style => ["cool", "and", "awesome"])

In your integration test you can then do:

test "get photos" do
   get "/photos/10/style/cool"
   assert_response :success
end