Veerasundaravel's Ruby on Rails Weblog

October 22, 2010

Testing Restful Routes from Console

Filed under: Ruby On Rails — Tags: , , , , , , , — Veerasundaravel @ 10:28 pm

When me and my friend discussed about advanced Restful routings concept, he asked about testing the route specification in rails console. Yes that kind of testing will help more on testing.

After surfing internet, he found the available option for it. Here I described that feature with some basic example.

Lets starts with sample rails app generation:

rails routes_testing
cd routes_testing

Then create your required models and controllers. Lets say we are going to create a controller named categories.

Now open the routes.rb files under the config folder of your application. Let’s navigate down to the block below:

# Sample resource route (maps HTTP verbs to controller actions automatically):
# map.resources :products

Let’s insert the following simple route right underneath the previous code:

map.resources :categories

So we finished our routes specification. Lets move to our Rails console.

ruby script/console

To test our route on the command line, the first thing we need to do is include the ActionController::UrlWriter module:

>> include ActionController::UrlWriter

And from here all of our route helpers (*_path and *_url) are available from the console.

>> categories_path
=> “/categories”
>> new_category_path
=> “/category/new”
>> edit_category_path(:id => 1)
=> ”/category/1/edit”
>> edit_category_path(:id => 1, :site_id=>2)
=> ”/category/1/edit?site_id=2”

Hence all of your routes specification can be nested via Rails Console very easily.

And alternatively, you can use the ActionController::Integration::Session object that is available at the console with the name “app”:

>> app.categories_path
=> “/categories”

%d bloggers like this: