When I load script/console
, some times I want play with the output of a controller or a view helper method.
Are there ways to:
- simulate a request?
- call methods from a controller instance on said request?
- test helper methods, either via said controller instance or another way?
An easy way to call a controller action from script/console and view/manipulate the response object is:
The app object is an instance of ActionController::Integration::Session
This works for me using Rails 2.1 and 2.3, I did not try earlier versions.
To call helpers, use the
helper
object:If you want to use a helper that's not included by default (say, because you removed
helper :all
fromApplicationController
), just include the helper.As for dealing with controllers, I quote Nick's answer:
Another way to do this is to use the rails debugger. There's a Rails Guide about debugging at http://guides.rubyonrails.org/debugging_rails_applications.html
Basically, start the server with the -u option:
And then insert a breakpoint into your script where you would like to have access to the controllers/helpers/etc..
And when you make a request and hit that part in the code, the server console will return a prompt where you can then make requests, view objects, etc.. from a command prompt. When finished, just type 'cont' to continue execution. There are also options for extended debugging, but this should at least get you started.
Here is how to make an authenticated POST request, using Refinery as an example:
You might find these useful too if you get an error:
If you need to test from the console (tested on Rails 3.1 and 4.1):
Call Controller Actions:
ApplicationController methods:
Route Helpers:
View Helpers:
Render:
ActiveSupport methods:
Lib modules:
Here's one way to do this through the console:
Creating a new instance of
ActionView::Base
gives you access to the normal view methods that your helper likely uses. Then extendingYourHelperModule
mixes its methods into your object letting you view their return values.