Last Updated: January 28, 2019
·
4.751K
· maximed

Rails console and `app.get` result in the browser

If you have ever used app from the rails console, you should know it allows you to issue requests to your application the same way your browser would do.
For instance, accessing the home page is as easy as [1]:

app.get root_path

The basics

Now, you can even see the response body with app.response.body. But what if the response becomes too large to be easily glanced in your terminal, or if it includes some html tag? Reading it from the console might tend to be impossible.

To ease your pain, you can define a method that would write the response to a file:

def write_response file_path = nil
  file_path   ||= "#{Rails.root}/tmp/response.#{response_type}"
  File.open( file_path, 'w' ) { |file| file.write app.response.body }
end

From here, you just have to open your browser to that file and it will be we just like if you have done it for real.

Don't define it every time!

Don't forget you can save methods to your shell! Adding above lines to your .pryrc will allow you to access this method every time you launch the rails console.

Going further

Of course for normal pages, this is not of much interest, but if your application has an API and you need to log from here to issue requests, you can define something like the following:

class ApiHelper
  # give access to named routes
  include Rails.application.routes.url_helpers

  # if you login to your api via a token
  attr_accessor :token
  attr_reader   :app

  # be sure to share the same session of app!
  def initialize(app)
    @app = app
  end

  # login a user
  def log user, password
    @app.post api_v1_login_path, {
                                     user: {
                                             login:        user.login,
                                             password:     password,
                                           }
                                   }

    @token = JSON.parse(@app.response.body)["data"]["authentication_token"]
  end

  # write server response to file
  def write_response file_path = nil
    # return if no request has been made
    return "No response from app... Did you issue one?" unless @app.response

    # get response type (html, json, ...)
    response_type = @app.response.content_type.to_s[/\w+\/(\w+)/, 1]

    # if no file_path has been supplied, write it to tmp
    file_path   ||= "#{Rails.root}/tmp/response.#{response_type}"

    File.open( file_path, 'w' ) { |file| file.write @app.response.body }

    # be nice and print the link pointing to the file
    "file://#{file_path}"
  end

To use it:

# instanciate a new ApiHelper
api = ApiHelper.new app

# log a user
api.log User.first, 'password'

# write response to a file readable by your browser
api.write_response
#=> "file:///home/coder/rails/project/tmp/response.json"
  1. To access named routes, you must include Rails.application.routes.url_helpers