Call URLs on your app from the Rails console
Feb 06 ’08
Here's a neat trick I just learned from Obie Fernandez (The Rails Way, p. 30): you can see what your Rails app's HTML output is from the console. To make this work you have to fool the app into thinking that there's a request coming in by setting some environmental variables, and then call the dispatcher.
But wouldn't it be nice to have a single method call, that uses url_for syntax?
class Object
def request(options = {})
method = options.delete(:method) || :get
options.reverse_merge!(:only_path => true)
ENV['REQUEST_URI'] = app.url_for(options)
ENV['REQUEST_METHOD'] = method.to_s
Dispatcher.dispatch
end
end
First we pull the method (:get, :post etc.) out, if it exists. By default we want it to be :get. Then we call url_for and have it only return the path, without any leading domain info. Next we populate the environmental variables and call the dispatcher. The return output will be the HTML your app renders.
To make the trick universally accessible on your development box, put the above code in ~/.irbrc:
Then, fire up the console to your favorite rails app, and call:
>> request(:controller => 'my_controller', :action => 'the_action')
You should see the HTML output scroll by.
Conversation in progress…
Join the conversation
* indicates a required field









On May 18th karatedog said:
It seems that it doesn't work in Rails 2.3.2, nor does what Obie Fernandez suggests in that book.
On July 29th Greg Moreno said:
I also had issue running Obie's example in console. I get this error message:
>> Dispatcher.dispatch
NoMethodError: undefined method `env_table' for nil:NilClass
On January 14th Max said:
Just came here via a Google search to find the solution to the non-working example in The Rails Way. Neither work for me.
There's a Lighthouse ticket open, but it's been open almost a year now...
https://awprorubyseries.lighthouseapp.com/projects/6454/tickets/161-dispatcherdispatch-does-not-work-p-30-for-rails-232