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”

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: