Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I call controller/view helper methods from the console in Ruby on Rails?

When I load script/console, sometimes I want to 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?
like image 836
kch Avatar asked Sep 29 '08 22:09

kch


People also ask

Can we use helper method in controller Rails?

In Rails 5, by using the new instance level helpers method in the controller, we can access helper methods in controllers.

What is helper method in Ruby on Rails?

A helper is a method that is (mostly) used in your Rails views to share reusable code. Rails comes with a set of built-in helper methods. One of these built-in helpers is time_ago_in_words .


2 Answers

To call helpers, use the helper object:

$ ./script/console >> helper.number_to_currency('123.45') => "R$ 123,45" 

If you want to use a helper that's not included by default (say, because you removed helper :all from ApplicationController), just include the helper.

>> include BogusHelper >> helper.bogus => "bogus output" 

As for dealing with controllers, I quote Nick's answer:

> app.get '/posts/1' > response = app.response # you now have a rails response object much like the integration tests  > response.body            # get you the HTML > response.cookies         # hash of the cookies  # etc, etc 
like image 118
kch Avatar answered Nov 04 '22 11:11

kch


An easy way to call a controller action from a script/console and view/manipulate the response object is:

> app.get '/posts/1' > response = app.response # You now have a Ruby on Rails response object much like the integration tests  > response.body            # Get you the HTML > response.cookies         # Hash of the cookies  # etc., etc. 

The app object is an instance of ActionController::Integration::Session

This works for me using Ruby on Rails 2.1 and 2.3, and I did not try earlier versions.

like image 45
Nick B Avatar answered Nov 04 '22 10:11

Nick B