Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a valid Authenticity Token with my Rails Console?

I am trying to use my rails console to call a public post method in my controller.

rails c

app.post '/servers/important_method'

This obviously gives me:

ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):

Is there any way to create a session and call that method?

EDIT: I could create a view and restart the production environment, but I'd like to avoid that.

like image 986
Joe Eifert Avatar asked Dec 02 '14 16:12

Joe Eifert


1 Answers

The key here is recognising app is an instance of ActionDispatch::Integration::Session, which includes ActionDispatch::TestProcess and therefore has a #session method that'll supply the authenticity token, once you've woken it up with a request.

We can then use this via the app::post helper, itself a simple wrapper for app's own #process method, which documents the calling parameters.

Putting all of those pieces together, in Rails 5 and later, we might write:

app.get ''
token = app.session[:_csrf_token]
app.post '/servers/important_method', params: { authenticity_token: token }

Note for older versions of Rails:
Since we're talking to the integration test API here, you may use similar forms in integration tests. When upgrading older Rails apps (v4 and earlier), you may find the following test code failing:

post '/servers/important_method', authenticity_token: token

and this should be revised to the new syntax, wrapping the parameters in params: { ... }.

like image 81
Stpn Avatar answered Oct 19 '22 05:10

Stpn